<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html lang="zh-cn" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<head>
    <base th:href="@{/}" href="">
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <title>TMS-沟通动态</title>
    <link rel="icon" th:href="@{/favicon.ico}" href="../../static/favicon.ico" type="image/x-icon" />
    <link rel="shortcut icon" th:href="@{/favicon.ico}" href="../../static/favicon.ico" type="image/x-icon" />
    <link rel="stylesheet" type="text/css" th:href="@{/lib/semantic/semantic.min.css}" href="../../static/lib/semantic/semantic.min.css" />
    <link rel="stylesheet" th:href="@{/lib/toastr/toastr.css}" href="../../static/lib/toastr/toastr.css" />
    <link rel="stylesheet" type="text/css" th:href="@{/admin/css/md-github.css}" href="../../static/admin/css/md-github.css" />
    <link rel="stylesheet" type="text/css" th:href="@{/lib/simplemde/simplemde.min.css}" href="../../static/lib/simplemde/simplemde.min.css" />
    <link rel="stylesheet" type="text/css" th:href="@{/lib/awesome/css/font-awesome.min.css}" href="../../static/lib/awesome/css/font-awesome.min.css" />
    <link rel="stylesheet" type="text/css" th:href="@{/lib/highlight/styles/github.css}" href="../../static/lib/highlight/styles/github.css" />
    <link rel="stylesheet" type="text/css" th:href="@{/lib/dropzone/basic.min.css}" href="../../static/lib/dropzone/basic.min.css" />
    <link rel="stylesheet" type="text/css" th:href="@{/lib/fancybox/jquery.fancybox.min.css}" href="../../static/lib/fancybox/jquery.fancybox.min.css" />
    <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/emojione/2.2.5/assets/css/emojione.min.css" />
    <link rel="stylesheet" type="text/css" th:href="@{/admin/css/admin.css}" href="../../static/admin/css/admin.css" />
    <style>
    body,
    html {
        height: auto;
    }
    
    body {
        position: relative!important;
    }
    
    .ui.dimmer {
        z-index: 2000;
    }
    
    .main.container {
        margin-right: 460px !important;
        margin-left: 3em !important;
        width: auto !important;
        max-width: 960px !important;
        padding: 2em 0em 7em;
        position: relative;
    }
    
    .main.container .right.rail {
        margin-left: 3em;
        padding-top: 2em;
        width: 420px;
        /*overflow: auto;*/
    }
    
    .main.container .right.rail .sticky {
        /*max-height: 400px;*/
        overflow: auto;
        padding-left: 5px;
        padding-right: 5px;
    }
    
    .CodeMirror,
    .CodeMirror-scroll {
        min-height: 150px;
    }
    
    .fm-edit-reply .CodeMirror,
    .fm-edit-reply .CodeMirror-scroll {
        min-height: 300px;
    }
    
    .CodeMirror-fullscreen,
    .editor-preview-side.editor-preview-active-side {
        z-index: 999;
    }
    
    .avatar.ui.mini.circular.image {
        cursor: pointer;
    }
    
    .ui.comments {
        max-width: none;
    }
    
    .ui.feed>.event:hover,
    .ui.comments .comment:hover,
    .ui.comments .comment.marked {
        background-color: #F3F3F3;
        -webkit-box-shadow: 0 0 5px 1px #0CC!important;
        -moz-box-shadow: 0 0 5px 1px #0CC!important;
        box-shadow: 0 0 5px 1px #0CC!important;
    }
    
    .ui.comments .comment:hover {
        z-index: 1991;
    }
    
    .ui.comments .comment:hover .toolbar {
        display: block;
    }
    /* .ui.comments .comment {
        overflow-y: auto;
    } */
    
    .ui.comments .comment .text {
        margin-top: 0.5em;
    }
    
    .ui.comments .comment .toolbar {
        display: none;
        position: absolute;
        right: 0;
        bottom: 0;
    }
    
    .ui.comments .comment .toolbar .reply {
        margin: 0;
    }
    
    .ui.comments .comment .toolbar .dd-quick-reply.ui.dropdown .menu {
        width: 160px;
        right: 0;
        left: auto;
    }
    
    .ui.feed>.event>.content .summary {
        /*font-size: 0.9em;*/
    }
    
    .ui.comments .comment .text span.at-user,
    .ui.comments .comment .text span.at-group,
    .pp-translate .user-group,
    .pp-translate .group-user,
    .pp-translate .ui.items>.item>.content>.description .at-user {
        cursor: pointer;
    }
    
    .ui.comments .comment a.author {
        color: #4183c4;
    }
    
    .ui.comments .comment {
        padding-right: 7px;
        padding-bottom: 1px;
        margin-top: 0;
    }
    
    .comments .comment .content .actions .dd-more-actions .menu > .edit,
    .comments .comment .content .actions .dd-more-actions .menu > .delete {
        display: none;
    }
    
    .ui.vertical.icon.buttons.btns-scroll {
        position: fixed;
        right: 433px;
        /*bottom: 325px;*/
        bottom: 220px;
        background-color: transparent;
        z-index: 1;
    }
    
    .ui.button.btn-get-chat-news {
        display: none;
        position: fixed;
        right: 430px;
        top: 250px;
        /* bottom: 400px; */
        background-color: rgba(219, 40, 40, 0.54);
        z-index: 1;
    }
    
    .ui.button.btn-get-chat-ats {
        display: none;
        position: fixed;
        right: 430px;
        top: 150px;
        background-color: rgba(219, 40, 40, 0.54);
        z-index: 2;
    }
    
    .ui.button.btn-get-chat-stows {
        /*display: none;*/
        position: fixed;
        right: 430px;
        top: 200px;
        background-color: rgba(219, 40, 40, 0.54);
        z-index: 1;
    }
    
    .ui.button.btn-chat-s2h {
        display: none;
        position: fixed;
        left: 205px;
        top: 162px;
        background-color: rgba(224, 225, 226, 0.54);
        z-index: 1992;
    }
    
    .ui.button.btn-chat-s2b {
        display: none;
        position: fixed;
        left: 205px;
        top: 200px;
        background-color: rgba(224, 225, 226, 0.54);
        z-index: 1992;
    }
    
    .ui.button.btn-chat-s2b:hover,
    .ui.button.btn-chat-s2h:hover {
        background-color: rgba(224, 225, 226, 1);
    }
    
    .ui.button.btn-get-chat-news:hover {
        background-color: rgba(219, 40, 40, 1);
    }
    
    .ui.vertical.icon.buttons.btns-scroll .button {
        border-radius: 10em!important;
        background-color: rgba(224, 225, 226, 0.54);
    }
    
    .ui.vertical.icon.buttons.btns-scroll .button:hover {
        background-color: rgba(224, 225, 226, 1);
    }
    /* 翻译popup样式 start*/
    
    .pp-translate .meta {
        border-top: 1px lightgray solid;
        border-bottom: 1px lightgray solid;
        padding-top: 5px;
        padding-bottom: 5px;
    }
    
    .pp-translate .extra {
        border-top: 1px lightgray solid;
    }
    
    .pp-translate .description {
        border-bottom: 1px lightgray solid;
        padding-bottom: 5px;
    }
    /* 翻译popup样式 end */
    /* chat msg search start */
    
    .chat-search {
        position: fixed;
        top: 50px;
        right: 433px;
        z-index: 4;
        height: 45px;
        /* display: none; */
        /* width: 30px; */
    }
    
    .ui.search.sh-search {
        /* display: none; */
    }
    
    .ui.circular.icon.button.btn-chat-search {
        margin-right: 0px;
    }
    
    .ui.icon.btn-search.circular.button {
        margin-right: 0;
    }
    
    .btn-chat-dir {
        display: none;
        position: fixed;
        top: 100px;
        right: 433px;
        margin-right: 0!important;
        z-index: 3;
    }
    
    .chat-search-loc {
        position: fixed;
        top: 50px;
        right: 433px;
        /* z-index: 1; */
        height: 36px;
        width: 1px;
    }
    
    .list-chat-search-results {
        min-width: 390px;
    }
    /* chat msg search end */
    /* 文件上传 start*/
    
    .dz-default.dz-message {
        height: 120px;
        line-height: 120px;
        width: 200px;
        text-align: center;
    }
    
    .editor-toolbar {
        z-index: 2;
    }
    
    .editor-toolbar.fullscreen {
        /* z-index: 1000!important; */
        z-index: 1993!important;
        overflow: visible;
    }
    /* 文件上传 end*/
    
    .ui.segment.wiki-dir {
        display: none;
        position: fixed;
        top: 86px;
        right: 0;
        overflow: auto;
        width: 469px;
        height: 430px;
        text-align: left;
    }
    
    a.item.wiki-dir-item {
        font-weight: normal;
    }
    
    .btn-custom-chat-refresh {
        position: fixed;
        bottom: 120px;
        right: 433px;
        z-index: 1;
    }
    
    .btn-chat-more {
        margin-bottom: 10px!important;
    }
    
    .btn-chat-pre-more {
        margin-top: 10px!important;
    }
    
    .pp-ats-content .list .item .preview.icon,
    .pp-ats-content .list .item .actions,
    .pp-stows-content .list .item .preview.icon,
    .pp-stows-content .list .item .actions {
        display: none;
    }
    
    .pp-ats-content .list .item:hover .preview.icon,
    .pp-stows-content .list .item:hover .preview.icon {
        display: table-cell;
    }
    
    .pp-ats-content .list .item:hover .actions,
    .pp-stows-content .list .item:hover .actions {
        display: block;
    }
    
    .pp-comment-reply {
        z-index: 1992!important;
    }
    /* Mobile */
    
    @media only screen and (max-width: 767px) {
        .comments .comment .content .actions > a.edit,
        .comments .comment .content .actions > a.delete {
            display: none;
        }
        .comments .comment .content .actions .dd-more-actions .menu > .edit,
        .comments .comment .content .actions .dd-more-actions .menu > .delete {
            display: block;
        }
        .ui.button.btn-chat-s2b,
        .ui.button.btn-chat-s2h {
            left: 15px;
        }
        .btn-chat-dir {
            left: 15px;
            right: auto;
        }
        .wiki-dir {
            left: 15px;
            right: auto;
        }
        .pp-comment-reply {
            z-index: 1990!important;
        }
    }
    /* Tablet */
    
    @media only screen and (min-width: 768px) and (max-width: 991px) {
        .ui.button.btn-chat-s2b,
        .ui.button.btn-chat-s2h {
            left: 165px;
        }
        .btn-chat-dir {
            left: 165px;
            right: auto;
        }
        .wiki-dir {
            left: 165px;
            right: auto;
        }
    }
    /* Mobile & Tablet */
    
    @media only screen and (max-width: 991px) {
        .main.container {
            margin-right: 0 !important;
            margin-left: 0 !important;
            width: auto !important;
            max-width: 960px !important;
            padding: 2em 0em 2em;
            position: relative;
        }
        .main.container .right.rail {
            margin-left: 3em;
            padding-top: 2em;
            width: 420px;
            display: none;
        }
        .ui.vertical.icon.buttons.btns-scroll {
            right: 13px;
            bottom: 190px;
        }
        .btn-custom-chat-refresh {
            bottom: 110px;
            right: 13px;
        }
        .ui.button.btn-get-chat-news {
            right: 10px;
            top: auto;
            bottom: 265px;
        }
        .chat-search {
            display: none;
        }
        .ui.button.btn-get-chat-ats {
            display: none!important;
        }
        .ui.button.btn-get-chat-stows {
            display: none!important;
        }
    }
    
    .cbutton {
        position: relative;
    }
    
    .cbutton::after {
        position: absolute;
        top: 50%;
        left: 50%;
        margin: -7px 0 0 -7px;
        width: 14px;
        height: 14px;
        border-radius: 50%;
        content: '';
        opacity: 0;
        pointer-events: none;
    }
    /* Novak */
    
    .cbutton--effect-novak::after {
        background: rgba(111, 148, 182, 0.25);
    }
    
    .cbutton--effect-novak.cbutton--click::after {
        -webkit-animation: anim-effect-novak 0.5s forwards;
        animation: anim-effect-novak 0.5s forwards;
    }
    
    @-webkit-keyframes anim-effect-novak {
        0% {
            opacity: 1;
            -webkit-transform: scale3d(0.1, 0.1, 1);
            transform: scale3d(0.1, 0.1, 1);
        }
        100% {
            opacity: 0;
            -webkit-transform: scale3d(8, 8, 1);
            transform: scale3d(30, 30, 1);
        }
    }
    
    @keyframes anim-effect-novak {
        0% {
            opacity: 1;
            -webkit-transform: scale3d(0.1, 0.1, 1);
            transform: scale3d(0.1, 0.1, 1);
        }
        100% {
            opacity: 0;
            -webkit-transform: scale3d(8, 8, 1);
            transform: scale3d(30, 30, 1);
        }
    }
    
    .pp-chat-emoji,
    .pp-chat-edit-emoji {
        width: 290px;
    }
    
    .pp-chat-emoji img.emojione:hover,
    .pp-chat-edit-emoji img.emojione:hover {
        background-color: lightgray;
    }
    
    .btn-wiki-dir-lock {
        position: absolute;
        top: 0;
        left: 0;
    }
    
    .ui.segment.pp-ats {
        display: none;
        position: fixed;
        top: 150px;
        right: 0;
        /*overflow: auto;*/
        width: 469px;
        /*height: 430px;*/
        text-align: left;
    }
    
    .pp-ats-lock {
        position: absolute;
        top: 0;
        left: 0;
        color: rgba(0, 0, 0, .87);
    }
    
    .pp-ats-refresh {
        position: absolute;
        top: 0;
        left: 30px;
        color: rgba(0, 0, 0, .87);
    }
    
    .pp-ats-remove {
        position: absolute;
        top: 0;
        right: -3px;
        color: rgba(0, 0, 0, .87);
    }
    
    .pp-ats .pp-ats-content .ui.list .item {
        font-weight: normal;
    }
    
    .ui.segment.pp-stows {
        display: none;
        position: fixed;
        top: 186px;
        right: 0;
        /*overflow: auto;*/
        width: 469px;
        /*height: 430px;*/
        text-align: left;
    }
    
    .pp-stows-lock {
        position: absolute;
        top: 0;
        left: 0;
        color: rgba(0, 0, 0, .87);
    }
    
    .pp-stows-refresh {
        position: absolute;
        top: 0;
        left: 30px;
        color: rgba(0, 0, 0, .87);
    }
    
    .pp-stows .pp-stows-content .ui.list .item {
        font-weight: normal;
    }
    </style>
    <script th:replace="admin/template :: baiduTongji"></script>
</head>

<body>
    <div th:replace="admin/index :: sidebar-menu"></div>
    <div th:replace="admin/index :: top-fixed-menu"></div>
    <div class="pusher ad-index-content" style="padding-bottom: 0;">
        <div class="ad-index-container">
            <div th:replace="admin/index :: rail-menu"></div>
            <div id="context">
                <!-- <div th:replace="admin/template :: ad-page-header ('沟通动态', 'dynamic')"></div> -->
                <div class="main ui container" style="padding-top: 3px;">
                    <div class="ui dividing right rail" style="min-height: 279px; padding-left: 1rem; padding-top: 0;">
                        <div class="ui sticky sy-dynamic" style="z-index: 0; top: 0px; padding-bottom: 20px;">
                            <h3 class="ui dividing header">动态</h3>
                            <div class="ui feed fd-dynamic">
                                <div class="event" th:each="l : ${logs}" th:attr="data-id=${l.id}">
                                    <div class="label">
                                        <a class="avatar ui mini circular image" style="width: 35px; height: 35px; font-size: 35px; background-color: rgba(150, 178, 183, 0.4); text-align: center;">
                                            <span style="display: inline-block; height: 35px; line-height: 35px; vertical-align: top;" th:if="${not #strings.isEmpty(l.creator.name)}" th:text="${#strings.toUpperCase(#strings.substring(l.creator.name,#strings.length(l.creator.name) - 1,#strings.length(l.creator.name)))}">管理员</span>
                                            <img th:if="${#strings.isEmpty(l.creator.name)}" th:src="@{/image/head.png}" src="../../static/image/head.png">
                                        </a>
                                    </div>
                                    <div class="content">
                                        <div class="summary">
                                            <a class="user" th:attr="data-value=${l.creator.username}" th:text="${#strings.isEmpty(l.creator.name) ? l.creator.username : l.creator.name}">张三</a>
                                            <span th:if="${#strings.toString(l.action) == 'Create'}">添加</span>
                                            <span th:if="${#strings.toString(l.action) == 'Update'}">更新</span>
                                            <span th:if="${#strings.toString(l.action) == 'Delete'}">删除</span>
                                            <a th:if="${#strings.toString(l.target) == 'Translate'}" target="_blank" th:href="@{/admin/translate(id=${l.targetId})}" th:text="${'翻译#' + l.targetId}">翻译</a>
                                            <span th:if="${#strings.toString(l.properties) == 'TranslateItem'}">内容</span>
                                            <span th:if="${#strings.toString(l.properties) == 'Key'}">名称</span>
                                            <span th:if="${#strings.toString(l.properties) == 'Watchers'}">关注者</span>
                                            <span th:if="${#strings.toString(l.properties) == 'Labels'}">标签</span>
                                            <div class="date timeago" th:title="${#calendars.format(l.createDate,'yyyy/MM/dd HH:mm:ss')}" th:text="${#calendars.format(l.createDate,'yyyy/MM/dd HH:mm:ss')}">
                                                1 Hour Ago
                                            </div>
                                        </div>
                                        <div th:unless="${#strings.isEmpty(l.properties)}" class="extra text">
                                            <div style="word-break: break-all; font-size: .85714286rem; color: rgba(0,0,0,.6);" th:unless="${l.oldValue == null}" th:text="${l.oldValue}"></div>
                                            <div class="divider fitted horizontal ui" style="color: green; font-size: 12px; font-weight: bold;" th:unless="${l.oldValue == null}">更新为</div>
                                            <div th:if="${#strings.toString(l.properties) == 'Labels'}" class="ui tag label" th:text="${l.newValue}"></div>
                                            <div th:if="${#strings.toString(l.properties) == 'Watchers'}" class="ui label">
                                                <i class="user icon"></i> <span class="mapping-user" th:text="${l.newValue}"></span>
                                            </div>
                                            <div style="word-break: break-all; font-size: .85714286rem; color: rgba(0,0,0,.6);" th:unless="${#strings.toString(l.properties) == 'Labels' or #strings.toString(l.properties) == 'Watchers'}" th:text="${l.newValue}"></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <button th:unless="${logs.last}" class="fluid ui basic button btn-log-more" th:text="${'加载更多(' + (logs.totalElements - (logs.number + 1) * logs.size) + ')'}">加载更多</button>
                        </div>
                    </div>
                    <div class="chat">
                        <div class="ui minimal comments" style="display:none;">
                            <h3 class="ui dividing header" style="margin-top: 65px;">沟通</h3>
                            <button th:unless="${chats.last}" class="fluid ui basic button btn-chat-more" th:text="${'加载更多(' + (chats.totalElements - (chats.number + 1) * chats.size) + ')'}">加载更多</button>
                            <div class="animated bounceInLeft comment" th:each="c : ${chats}" th:classappend="${(param.containsKey('id') and #strings.equals(param.id[0], c.id)) ? 'marked' : ''}" th:attr="data-id=${c.id}, data-version=${c.version}">
                                <a class="avatar ui mini circular image" th:attr="data-value=${c.creator.username}" style="width: 35px; height: 35px; font-size: 35px; background-color: rgba(150, 178, 183, 0.4); text-align: center;">
                                    <span style="display: inline-block; height: 35px; line-height: 35px; vertical-align: top;" th:if="${not #strings.isEmpty(c.creator.name)}" th:text="${#strings.toUpperCase(#strings.substring(c.creator.name,#strings.length(c.creator.name) - 1,#strings.length(c.creator.name)))}">管理员</span>
                                    <img th:if="${#strings.isEmpty(c.creator.name)}" th:src="@{/image/head.png}" src="../../static/image/head.png">
                                </a>
                                <div class="content">
                                    <a class="author" th:attr="data-value=${c.creator.username}" th:text="${#strings.isEmpty(c.creator.name) ? c.creator.username : c.creator.name}">Matt</a>
                                    <div class="metadata">
                                        <span class="date timeago" th:title="${c.createDate}" th:text="${#calendars.format(c.createDate,'yyyy/MM/dd HH:mm:ss')}">Today at 5:42PM</span>
                                        <div class="rating">
                                            <i style="cursor: pointer;" title="赞一下" class="cbutton cbutton--effect-novak thumbs outline up icon" data-type="zan" data-label="赞"></i> <span th:unless="${#strings.isEmpty(c.voteZan)}" th:title="${c.voteZan}" th:text="${#arrays.length(#strings.arraySplit(c.voteZan,',')) + ' 赞'}">5 赞</span>
                                        </div>
                                        <div class="rating">
                                            <i style="cursor: pointer;" title="踩一下" class="cbutton cbutton--effect-novak thumbs outline down icon" data-type="cai" data-label="踩"></i> <span th:unless="${#strings.isEmpty(c.voteCai)}" th:title="${c.voteCai}" th:text="${#arrays.length(#strings.arraySplit(c.voteCai,',')) + ' 踩'}">5 踩</span>
                                        </div>
                                    </div>
                                    <div class="text markdown-body" th:attr="data-content=${c.content}" th:text="${c.content}">
                                        How artistic!
                                    </div>
                                    <div class="actions">
                                        <a class="reply">回复</a>
                                        <a class="stow">收藏</a>
                                        <a class="edit" title="Alt+双击" th:if="${#authorization.expression('hasRole(''ROLE_SUPER'')') or (c.creator.username == user.username) or (c.openEdit != null and c.openEdit)}">编辑</a>
                                        <a class="delete" th:if="${#authorization.expression('hasRole(''ROLE_SUPER'')') or (c.creator.username == user.username)}">删除</a>
                                        <div class="ui top right pointing dropdown dd-more-actions">
                                            <a class="text" style="margin: 0;">更多</a>
                                            <i class="dropdown icon" style="margin-left: 0px; margin-right: 5px;"></i>
                                            <div class="menu">
                                                <div class="edit item" title="Alt+双击" th:if="${#authorization.expression('hasRole(''ROLE_SUPER'')') or (c.creator.username == user.username) or (c.openEdit != null and c.openEdit)}">编辑</div>
                                                <div class="delete item" th:if="${#authorization.expression('hasRole(''ROLE_SUPER'')') or (c.creator.username == user.username)}">删除</div>
                                                <div class="item btn-read" title="Ctrl+双击">阅读</div>
                                                <div class="item btn-wiki" th:if="${#authorization.expression('hasRole(''ROLE_ADMIN'')') or (c.creator.username == user.username)}" th:if="${#strings.toString(c.type) != 'Wiki'}">转博</div>
                                                <div class="item btn-jira">转JIRA</div>
                                                <div class="item btn-openEdit" th:if="${#authorization.expression('hasRole(''ROLE_SUPER'')') or (c.creator.username == user.username)}" th:attr="data-value=${c.openEdit}" th:text="${(c.openEdit != null and c.openEdit) ? '关闭协作' : '开启协作'}">开启协作</div>
                                                <div class="item btn-copy" th:attr="data-clipboard-text=${c.content}">复制</div>
                                                <div class="item btn-share" th:attr="data-clipboard-text=${#httpServletRequest.getRequestURL() + '?id=' + c.id}">分享</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="toolbar">
                                    <div title="快捷回复" class="ui dropdown icon mini button reply dd-quick-reply">
                                        <i class="reply icon"></i>
                                        <div class="menu">
                                            <div class="ui icon input">
                                                <i class="send link icon"></i>
                                                <input type="text" name="reply" placeholder="快捷回复...">
                                            </div>
                                            <div class="item ok">
                                                <div class="ui red empty circular label"></div>
                                                <span class="text">好的!</span>
                                            </div>
                                            <div class="item got">
                                                <div class="ui blue empty circular label"></div>
                                                <span class="text">收到!</span>
                                            </div>
                                            <div class="item done">
                                                <div class="ui black empty circular label"></div>
                                                <span class="text">搞定!</span>
                                            </div>
                                            <div class="item ongoing">
                                                <div class="ui yellow empty circular label"></div>
                                                <span class="text">处理中!</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <button th:unless="${chats.first}" class="fluid ui basic button btn-chat-pre-more" th:text="${'加载更多(' + (chats.number * chats.size) + ')'}">加载更多</button>
                            <form class="ui reply form fm-reply">
                                <div class="field markdown-body pp-users dropzone" style="border: none;">
                                    <textarea autofocus="autofocus" class="ta-md"></textarea>
                                </div>
                                <div class="ui fluid popup bottom left transition hidden list-users-container" style="max-height:150px; overflow:auto;">
                                    <div class="ui middle aligned selection list list-users">
                                        <div class="item" th:attr="data-value=${'all'}, data-label=${'全部用户'}">
                                            <a class="avatar ui mini circular image" style="width: 35px; height: 35px; font-size: 35px; background-color: rgba(150, 178, 183, 0.4); text-align: center; padding-right: 0px;">
                                                <span style="display: inline-block; height: 35px; line-height: 35px; vertical-align: top;" th:text="${'全'}">全部用户</span>
                                            </a>
                                            <div class="content">
                                                <div class="header" th:text="${'全部用户 - (all)'}">全部用户 - (all)</div>
                                            </div>
                                        </div>
                                        <div class="item" th:each="u : ${users}" th:if="${u.enabled}" th:attr="data-value=${u.username}, data-label=${#strings.isEmpty(u.name) ? u.username : u.name}">
                                            <!-- <img class="ui avatar image" th:src="@{/image/head.png}" src="/images/avatar/small/helen.jpg"> -->
                                            <a class="avatar ui mini circular image" style="width: 35px; height: 35px; font-size: 35px; background-color: rgba(150, 178, 183, 0.4); text-align: center; padding-right: 0px;">
                                                <span style="display: inline-block; height: 35px; line-height: 35px; vertical-align: top;" th:if="${not #strings.isEmpty(u.name)}" th:text="${#strings.toUpperCase(#strings.substring(u.name,#strings.length(u.name) - 1,#strings.length(u.name)))}">管理员</span>
                                                <img style="height:35px;" th:if="${#strings.isEmpty(u.name)}" th:src="@{/image/head.png}" src="../../static/image/head.png">
                                            </a>
                                            <div class="content">
                                                <div class="header" th:text="${(#strings.isEmpty(u.name) ? u.username : u.name) + ' - ' + u.mails + ' (' + u.username + ')'}">张三 - weicheng.xi@newtouch.cn (xiweicheng)</div>
                                            </div>
                                        </div>
                                        <div class="item" th:each="g : ${groups}" th:attr="data-type=${'group'}, data-value=${g.groupName}, data-label=${g.groupName}">
                                            <a class="avatar ui mini circular image" style="width: 35px; height: 35px; font-size: 35px; background-color: rgba(150, 178, 183, 0.4); text-align: center; padding-right: 0px;">
                                                <span style="display: inline-block; height: 35px; line-height: 35px; vertical-align: top;" th:text="${#strings.toUpperCase(#strings.substring(g.groupName,#strings.length(g.groupName) - 1,#strings.length(g.groupName)))}">管理员</span>
                                            </a>
                                            <div class="content">
                                                <div class="header" th:text="${(g.groupName) + ' - (用户组)'}">张三 - (用户组)</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="ui buttons">
                                    <button class="cbutton cbutton--effect-novak ui button btn-chat-clear" title="取消(Esc)">取消</button>
                                    <div class="or"></div>
                                    <button class="cbutton cbutton--effect-novak ui positive button btn-chat-submit" title="提交(Ctrl+Enter)">提交</button>
                                </div>
                                <a th:href="@{/admin/dynamic(scroll=${'1'})}" title="刷新消息" class="pp-not ui black circular icon right floated button btn-custom-chat-refresh">
                                    <i class="refresh icon"></i>
                                </a>
                                <div class="ui right floated compact basic segment" style="margin-top: 0px; padding-top: 8px; margin-left: 0; padding-left: 0;">
                                    <div class="ui fitted toggle checkbox ck-auto-chat-refresh" title="开启自动刷新消息">
                                        <input type="checkbox">
                                        <label></label>
                                    </div>
                                </div>
                                <div class="ui right floated compact basic segment" style="margin-top: 0px; padding-top: 8px; margin-left: 0; padding-left: 0;">
                                    <div class="ui fitted toggle checkbox ck-only-at-msg" title="只提醒@沟通消息桌面通知">
                                        <input type="checkbox">
                                        <label></label>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="ui circular red icon button btn-get-chat-news" title="获取新消息">
                            <i class="refresh icon"></i>
                            <div class="floating ui red circular label lbl-chat-news-count">0</div>
                        </div>
                        <div class="ui circular icon button btn-chat-s2h" title="滚动至消息头(alt+up)"> <i class="chevron up icon"></i> </div>
                        <div class="ui circular icon button btn-chat-s2b" title="滚动至下个消息头(alt+down)"> <i class="chevron down icon"></i> </div>
                        <div class="ui vertical circular icon buttons btns-scroll">
                            <div class="ui circular icon button btn-scroll-up" title="滚动至顶部(ctrl+alt+up)">
                                <i class="arrow up icon"></i>
                            </div>
                            <div class="ui circular icon button btn-scroll-down" title="滚动至底部(ctrl+alt+down)">
                                <i class="arrow down icon"></i>
                            </div>
                        </div>
                        <!-- 沟通消息检索 -->
                        <div class="chat-search">
                            <div class="ui search">
                                <div class="ui circular icon button btn-search" title="沟通消息检索">
                                    <input style="display: none;" class="prompt" th:value="${param.containsKey('search') ? param.search[0] : ''}" type="text" placeholder="查找...">
                                    <i class="search link icon"></i>
                                </div>
                                <div class="results"></div>
                            </div>
                        </div>
                        <div class="ui circular icon button btn-chat-dir">
                            <i class="content icon"></i>
                            <div class="wiki-dir ui segment">
                                <i class="circular unlock alternate tiny icon btn-wiki-dir-lock"></i>
                                <div class="wiki-dir-tree" style="margin-top: 10px;"></div>
                            </div>
                        </div>
                        <div class="ui circular red icon button btn-get-chat-ats" title="查看@消息">
                            <i class="at icon"></i>
                            <div class="floating ui red circular label lbl-chat-ats-count">0</div>
                            <div class="pp-ats ui segment">
                                <i class="circular unlock alternate tiny icon pp-ats-lock"></i>
                                <i class="circular refresh tiny icon pp-ats-refresh"></i>
                                <i title="全部知悉" class="circular remove tiny icon pp-ats-remove"></i>
                                <div class="pp-ats-content" style="margin-top: 10px;">
                                    <div class="ui selection divided list" style="max-height:400px; overflow:auto;"></div>
                                </div>
                            </div>
                        </div>
                        <div class="ui circular red icon button btn-get-chat-stows" title="查看收藏消息">
                            <i class="star icon"></i>
                            <div class="pp-stows ui segment">
                                <i class="circular unlock alternate tiny icon pp-stows-lock"></i>
                                <i class="circular refresh tiny icon pp-stows-refresh"></i>
                                <div class="pp-stows-content" style="margin-top: 10px;">
                                    <div class="ui selection divided list" style="max-height:400px; overflow:auto;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- popup container start -->
    <div style="z-index: 1991;" class="ui flowing popup transition hidden pp-translate"></div>
    <div class="ui flowing popup transition hidden pp-comment-reply">
        <div class="ui minimal comments" style="max-height:180px; overflow-y:auto; padding: 5px;"></div>
    </div>
    <div class="chat-search-loc"></div>
    <div class="ui basic flowing popup top left transition hidden pp-chat-search-results">
        <div class="ui selection divided list list-chat-search-results" style="max-height: 500px; overflow: auto;">
        </div>
    </div>
    <div class="ui flowing popup top left transition hidden pp-chat-upload-file">
        <form action="/admin/file/upload" class="dropzone">
            <div class="fallback">
                <input name="file" type="file" multiple />
            </div>
            <input type="hidden" th:name="${_csrf != null ? _csrf.parameterName : ''}" th:value="${_csrf != null ? _csrf.token : ''}" />
        </form>
    </div>
    <div class="ui flowing popup top left transition hidden pp-chat-edit-upload-file">
        <form action="/admin/file/upload" class="dropzone">
            <div class="fallback">
                <input name="file" type="file" multiple />
            </div>
            <input type="hidden" th:name="${_csrf != null ? _csrf.parameterName : ''}" th:value="${_csrf != null ? _csrf.token : ''}" />
        </form>
    </div>
    <div class="ui flowing popup top left transition hidden pp-chat-emoji"></div>
    <div class="ui flowing popup top left transition hidden pp-chat-edit-emoji"></div>
    <!-- popup container end -->
    <div th:replace="admin/template :: ad-handle-confirm"></div>
    <div th:replace="admin/template :: ad-delete-confirm"></div>
    <div th:replace="admin/template :: ad-chat-edit"></div>
    <div th:include="admin/template :: ad-page-common"></div>
    <div th:replace="admin/template :: ad-page-dimmer"></div>
    <div th:replace="admin/template :: ad-comment-page-dimmer"></div>
    <div th:replace="admin/template :: chatMoreTpl"></div>
    <div th:replace="admin/template :: chatReplyTpl"></div>
    <div th:replace="admin/template :: logMoreTpl"></div>
    <div th:replace="admin/template :: tansPpTpl"></div>
    <div th:replace="admin/template :: chatMsgPpTpl"></div>
    <div th:replace="admin/template :: userInfoPpTpl"></div>
    <div th:replace="admin/template :: userGroupInfoPpTpl"></div>
    <div th:replace="admin/template :: allUserInfoPpTpl"></div>
    <div th:replace="admin/template :: chatSearchTpl"></div>
    <div th:replace="admin/template :: ad-msg-as-wiki"></div>
    <div th:replace="admin/template :: chatAtsTpl"></div>
    <div th:replace="admin/template :: chatStowsTpl"></div>
    <input type="hidden" name="page.number" th:value="${chats.number}" />
    <input type="hidden" name="page.number.next" th:value="${chats.number + 1}" />
    <input type="hidden" name="page.number.pre" th:value="${chats.number - 1}" />
    <input type="hidden" name="page.size" th:value="${chats.size}" />
    <input type="hidden" name="page.number.logs" th:value="${logs.number}" />
    <input type="hidden" name="page.number.next.logs" th:value="${logs.number + 1}" />
    <input type="hidden" name="page.size.logs" th:value="${logs.size}" />
    <input type="hidden" name="user.username" th:value="${user.username}" />
    <input type="hidden" name="role.admin" th:value="${#authorization.expression('hasRole(''ROLE_ADMIN'')')}" />
    <input type="hidden" name="role.super" th:value="${#authorization.expression('hasRole(''ROLE_SUPER'')')}" />
    <input type="hidden" th:each="u : ${users}" data-group="users" th:attr="data-status=${u.enabled}" th:name="${u.username}" th:value="${u.name}" />
    <script type="text/javascript" th:src="@{/admin/js/deps-base.js}" src="../../static/admin/js/deps-base.js"></script>
    <script type="text/javascript" th:src="@{/admin/js/deps-dynamic.js}" src="../../static/admin/js/deps-dynamic.js"></script>
    <script type="text/javascript" th:src="@{/lib/simplemde/simplemde.min.js}" src="../../static/lib/simplemde/simplemde.min.js"></script>
    <script type="text/javascript" th:src="@{/lib/jquery.hotkeys.js}" src="../../static/lib/jquery.hotkeys.js"></script>
    <script type="text/javascript" th:src="@{/lib/diff/diff.min.js}" src="../../static/lib/diff/diff.min.js"></script>
    <!-- <script type="text/javascript" th:src="@{/lib/jquery.textcomplete.min.js}" src="../../static/lib/jquery.textcomplete.min.js"></script> -->
    <!-- <script type="text/javascript" th:src="@{/lib/jquery.timeago.min.js}" src="../../static/lib/jquery.timeago.min.js"></script> -->
    <!-- <script type="text/javascript" th:src="@{/lib/desktop-notify-min.js}" src="../../static/lib/desktop-notify-min.js"></script> -->
    <!-- <script type="text/javascript" th:src="@{/lib/clipboard.min.js}" src="../../static/lib/clipboard.min.js"></script> -->
    <script type="text/javascript" src="//cdn.jsdelivr.net/emojione/2.2.5/lib/js/emojione.min.js"></script>
    <script type="text/javascript" th:src="@{/admin/js/admin.js}" src="../../static/admin/js/admin.js"></script>
    <!-- <script type="text/javascript" th:src="@{/admin/js/poll.js}" src="../../static/admin/js/poll.js"></script> -->
    <script type="text/javascript">
    jQuery(function($) {

        var baseURL = Utils.getBaseURL();

        Dropzone.autoDiscover = false;

        jQuery(".timeago").timeago();

        new Clipboard('.btn-share, .btn-copy').on('success', function(e) {
            var $btn = $(e.trigger);
            var msg = $btn.hasClass('btn-share') ? '分享链接复制到剪贴板成功!' : '沟通内容复制到剪贴板成功!';
            toastr.success(msg);
        }).on('error', function(e) {
            toastr.error('复制到剪贴板失败,可能您的浏览器不支持!');
        });

        new Clipboard('.btn-jira', {
            text: function(trigger) {
                var txt = $(trigger).siblings('.btn-copy').attr('data-clipboard-text');
                var href = $(trigger).siblings('.btn-share').attr('data-clipboard-text');
                var id = $(trigger).closest('.comment').attr('data-id');
                return 'h1. [TMS沟通消息({title})|{href}]\n----\n'
                    .replace(/\{title\}/g, '#' + id)
                    .replace(/\{href\}/g, href) + J2M.toJ(txt);
            }
        }).on('success', function(e) {
            toastr.success('复制[JIRA问题描述]到剪贴板成功!');
            Utils.openLink('http://220.248.17.34:7991/secure/CreateIssue!default.jspa');
        }).on('error', function(e) {
            toastr.error('复制到剪贴板失败,可能您的浏览器不支持!');
            Utils.openLink('http://220.248.17.34:7991/secure/CreateIssue!default.jspa');
        });

        // --------------------------------------------------------------------------------- var define start
        var allUserInfo = Utils.getAllUserInfo();
        // --------------------------------------------------------------------------------- var define end

        // --------------------------------------------------------------------------------- username mapping to name start
        Utils.showMappedTxt('.mapping-user');
        // --------------------------------------------------------------------------------- username mapping to name end

        // ------------------------------------------------------------------------------------- ck-auto-chat-refresh start

        var isFetchNews = false; // 是否正在获取沟通消息中
        var isOn = 0; // 聊天消息自动刷新开关状态

        if (localStorage) {
            var v = localStorage.getItem('admin/dynamic:auto-chat-refresh');
            isOn = v ? v : 0;
        }

        var $autoCR = $('.ck-auto-chat-refresh');
        $autoCR.checkbox({
            onChecked: function() {
                $autoCR.attr('title', '关闭自动刷新消息');
                $('.btn-custom-chat-refresh').hide();
                localStorage && localStorage.setItem('admin/dynamic:auto-chat-refresh', 1);
                window.poll.reset(); // 重置轮询频率
                getChatNews(); // 立即获取异常新消息
            },
            onUnchecked: function() {
                $autoCR.attr('title', '开启自动刷新消息');
                $('.btn-custom-chat-refresh').show();
                localStorage && localStorage.setItem('admin/dynamic:auto-chat-refresh', 0);
            }
        });

        if (isOn != 0) {
            $autoCR.checkbox('check');
        }

        // ------------------------------------------------------------------------------------- ck-auto-chat-refresh end

        // ------------------------------------------------------------------------------------- ck-only-at-msg start

        var isOnlyAtOn = 0; // 聊天消息自动刷新开关状态

        if (localStorage) {
            var v = localStorage.getItem('admin/dynamic:only-at-msg');
            isOnlyAtOn = v ? v : 0;
        }

        var $onlyAt = $('.ck-only-at-msg');
        $onlyAt.checkbox({
            onChecked: function() {
                localStorage && localStorage.setItem('admin/dynamic:only-at-msg', 1);
            },
            onUnchecked: function() {
                localStorage && localStorage.setItem('admin/dynamic:only-at-msg', 0);
            }
        });

        if (isOnlyAtOn != 0) {
            $onlyAt.checkbox('check');
        }

        // ------------------------------------------------------------------------------------- ck-only-at-msg end


        // ------------------------------------------------------------------------------------- fancybox image start

        $('body').on('click', '.comments .comment .content .text.markdown-body img, .pp-translate .description.markdown-body img', function(event) {
            event.preventDefault();
            $img = $(this);
            var imgArr = [];
            var $imgs = $img.closest('.markdown-body').find('img').each(function(index, img) {
                imgArr.push({
                    href: $(img).attr('src'),
                    title: $(img).attr('alt')
                });
            });
            var index = $imgs.index($img);
            $.fancybox.open(imgArr, {
                loop: false,
                index: index
            });
        });

        // ------------------------------------------------------------------------------------- fancybox image end


        // ------------------------------------------------------------------------------------- rating start

        $('body').on('click', '.comments .comment .content .rating i.outline.icon', function(event) {
            event.preventDefault();
            $icon = $(this).removeClass('outline');
            $span = $icon.parent().children('span');

            var chatHtml = $icon.closest('.comment').find('.content .text.markdown-body').html();
            var html = $('<div class="markdown-body"/>').html('<style>.markdown-body{font-size:14px;line-height:1.6}.markdown-body>:first-child{margin-top:0!important}.markdown-body>:last-child{margin-bottom:0!important}.markdown-body a.absent{color:#C00}.markdown-body a.anchor{bottom:0;cursor:pointer;display:block;left:0;margin-left:-30px;padding-left:30px;position:absolute;top:0}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6{cursor:text;font-weight:700;margin:20px 0 10px;padding:0;position:relative}.markdown-body h1 .mini-icon-link,.markdown-body h2 .mini-icon-link,.markdown-body h3 .mini-icon-link,.markdown-body h4 .mini-icon-link,.markdown-body h5 .mini-icon-link,.markdown-body h6 .mini-icon-link{color:#000;display:none}.markdown-body h1:hover a.anchor,.markdown-body h2:hover a.anchor,.markdown-body h3:hover a.anchor,.markdown-body h4:hover a.anchor,.markdown-body h5:hover a.anchor,.markdown-body h6:hover a.anchor{line-height:1;margin-left:-22px;padding-left:0;text-decoration:none;top:15%}.markdown-body h1:hover a.anchor .mini-icon-link,.markdown-body h2:hover a.anchor .mini-icon-link,.markdown-body h3:hover a.anchor .mini-icon-link,.markdown-body h4:hover a.anchor .mini-icon-link,.markdown-body h5:hover a.anchor .mini-icon-link,.markdown-body h6:hover a.anchor .mini-icon-link{display:inline-block}.markdown-body hr:after,.markdown-body hr:before{display:table;content:""}.markdown-body h1 code,.markdown-body h1 tt,.markdown-body h2 code,.markdown-body h2 tt,.markdown-body h3 code,.markdown-body h3 tt,.markdown-body h4 code,.markdown-body h4 tt,.markdown-body h5 code,.markdown-body h5 tt,.markdown-body h6 code,.markdown-body h6 tt{font-size:inherit}.markdown-body h1{color:#000;font-size:28px}.markdown-body h2{border-bottom:1px solid #CCC;color:#000;font-size:24px}.markdown-body h3{font-size:18px}.markdown-body h4{font-size:16px}.markdown-body h5{font-size:14px}.markdown-body h6{color:#777;font-size:14px}.markdown-body blockquote,.markdown-body dl,.markdown-body ol,.markdown-body p,.markdown-body pre,.markdown-body table,.markdown-body ul{margin:15px 0}.markdown-body hr{overflow:hidden;background:#e7e7e7;height:4px;padding:0;margin:16px 0;border:0;-moz-box-sizing:content-box;box-sizing:content-box}.markdown-body h1+p,.markdown-body h2+p,.markdown-body h3+p,.markdown-body h4+p,.markdown-body h5+p,.markdown-body h6+p,.markdown-body ol li>:first-child,.markdown-body ul li>:first-child{margin-top:0}.markdown-body hr:after{clear:both}.markdown-body a:first-child h1,.markdown-body a:first-child h2,.markdown-body a:first-child h3,.markdown-body a:first-child h4,.markdown-body a:first-child h5,.markdown-body a:first-child h6,.markdown-body>h1:first-child,.markdown-body>h1:first-child+h2,.markdown-body>h2:first-child,.markdown-body>h3:first-child,.markdown-body>h4:first-child,.markdown-body>h5:first-child,.markdown-body>h6:first-child{margin-top:0;padding-top:0}.markdown-body li p.first{display:inline-block}.markdown-body ol,.markdown-body ul{padding-left:30px}.markdown-body ol.no-list,.markdown-body ul.no-list{list-style-type:none;padding:0}.markdown-body ol ol,.markdown-body ol ul,.markdown-body ul ol,.markdown-body ul ul{margin-bottom:0}.markdown-body dl{padding:0}.markdown-body dl dt{font-size:14px;font-style:italic;font-weight:700;margin:15px 0 5px;padding:0}.markdown-body dl dt:first-child{padding:0}.markdown-body dl dt>:first-child{margin-top:0}.markdown-body dl dt>:last-child{margin-bottom:0}.markdown-body dl dd{margin:0 0 15px;padding:0 15px}.markdown-body blockquote>:first-child,.markdown-body dl dd>:first-child{margin-top:0}.markdown-body blockquote>:last-child,.markdown-body dl dd>:last-child{margin-bottom:0}.markdown-body blockquote{border-left:4px solid #DDD;color:#777;padding:0 15px}.markdown-body table th{font-weight:700}.markdown-body table td,.markdown-body table th{border:1px solid #CCC;padding:6px 13px}.markdown-body table tr{background-color:#FFF;border-top:1px solid #CCC}.markdown-body table tr:nth-child(2n){background-color:#F8F8F8}.markdown-body img{max-width:100%}.markdown-body span.frame{display:block;overflow:hidden}.markdown-body span.frame>span{border:1px solid #DDD;display:block;float:left;margin:13px 0 0;overflow:hidden;padding:7px;width:auto}.markdown-body span.frame span img{display:block;float:left}.markdown-body span.frame span span{clear:both;color:#333;display:block;padding:5px 0 0}.markdown-body span.align-center{clear:both;display:block;overflow:hidden}.markdown-body span.align-center>span{display:block;margin:13px auto 0;overflow:hidden;text-align:center}.markdown-body span.align-center span img{margin:0 auto;text-align:center}.markdown-body span.align-right{clear:both;display:block;overflow:hidden}.markdown-body span.align-right>span{display:block;margin:13px 0 0;overflow:hidden;text-align:right}.markdown-body span.align-right span img{margin:0;text-align:right}.markdown-body span.float-left{display:block;float:left;margin-right:13px;overflow:hidden}.markdown-body span.float-left span{margin:13px 0 0}.markdown-body span.float-right{display:block;float:right;margin-left:13px;overflow:hidden}.markdown-body span.float-right>span{display:block;margin:13px auto 0;overflow:hidden;text-align:right}.markdown-body code,.markdown-body tt{background-color:#F8F8F8;border:1px solid #EAEAEA;border-radius:3px;margin:0 2px;padding:0 5px;white-space:nowrap}.markdown-body pre>code{background:none;border:none;margin:0;padding:0;white-space:pre}.markdown-body .highlight pre,.markdown-body pre{background-color:#F8F8F8;border:1px solid #CCC;border-radius:3px;font-size:13px;line-height:19px;overflow:auto;padding:6px 10px}.markdown-body pre code,.markdown-body pre tt{background-color:transparent;border:none}</style>' + chatHtml).wrap('<div/>').parent().html();

            $.post('/admin/chat/vote/unmask', {
                baseURL: baseURL,
                id: $icon.closest('.comment').attr('data-id'),
                type: $icon.attr('data-type'),
                contentHtml: html
            }, function(data, textStatus, xhr) {
                if (data.success) {
                    if ($span.size() == 0) {
                        $span = $('<span>1 ' + $icon.attr('data-label') + '</span>');
                        $icon.parent().append($span);
                    } else {
                        var oArr = $span.text().split(' ');
                        $span.text((parseInt(oArr[0]) + 1) + ' ' + oArr[1]);
                    }
                    $span.attr('title', $icon.attr('data-type') == 'zan' ? data.data.voteZan : data.data.voteCai)
                } else {
                    toastr.error(data.data, "投票失败!");
                }
            });
        });

        // ------------------------------------------------------------------------------------- rating end

        // ------------------------------------------------------------------------------------- chat search start
        $('.chat-search').hover(function() {
            $(this).find('input').show();
            $(this).find('.btn-search').removeClass('circular button').addClass('input');
            var $input = $(this).find('input');

            if (!$input.val()) {
                var loginUsername = $('input:hidden[name="user.username"]').val();
                $input.val('is:' + loginUsername + ':');
            }

            $input.focus().select();
        }, function() {
            $(this).find('input').hide();
            $(this).find('.btn-search').removeClass('input').addClass('circular button');
        });
        var source = [];
        if (localStorage) {
            var v = localStorage.getItem('admin/dynamic:search');
            source = v ? $.parseJSON(v) : [];
        }
        $('.chat-search .ui.search').search({
            source: source,
            onSelect: function(result, response) {
                searchHandler();
            },
            onResults: function() {
                $(this).search('hide results');
            }
        });

        // 检索前检查
        function searchPreCheck() {
            var search = $('.chat-search .ui.search input').val();

            if (!search) {
                return false;
            }
            if (search.length < 2) {
                toastr.error('检索条件不能少于2位字符!');
                return false;
            }
            // 保存检索值
            var isExists = false;
            $.each(source, function(index, val) {
                if (val.title == search) {
                    isExists = true;
                    return false;
                }
            });
            if (!isExists) {
                source.splice(0, 0, {
                    title: search
                });
                $('.chat-search .ui.search').search({
                    source: source
                });
            }
            localStorage && localStorage.setItem('admin/dynamic:search', JSON.stringify(source));
            return true;
        }

        function searchHandler() {
            $ppSearch.popup('hide');
            if ($ppSearch.popup('is visible')) {
                $ppSearch.popup('hide');
                setTimeout(function() {
                    $ppSearch.popup('show');
                }, 300);
            } else {
                $ppSearch.popup('show');
            }
        }

        var $ppSearch = $('.btn-search i.icon').popup({
            popup: $('.pp-chat-search-results'),
            hoverable: true,
            on: 'click',
            inline: false,
            // maxSearchDepth: 50,
            // target: '.btn-search i.icon',
            movePopup: false,
            observeChanges: false,
            position: 'bottom right',
            closable: false,
            hideOnScroll: false,
            delay: {
                show: 300,
                hide: 300
            },
            onShow: function() {
                if (!searchPreCheck()) {
                    return false;
                }
                var $pp = $(this);
                var search = $('.chat-search .ui.search input').val();
                $pp.children('.ui.list').html('加载中...');
                $.get('admin/chat/search/unmask', {
                    size: 100,
                    search: search
                }, function(data) {
                    if (data.success) {
                        var chats = data.data.content;
                        if (data.data.content.length == 0) {
                            $pp.children('.ui.list').html('检索结果不存在!');
                            return;
                        }

                        $.each(chats, function(index, chat) {
                            chat.contentBrief = chat.content.length > 50 ? chat.content.substr(0, 47) + '...' : chat.content;
                            if (chat.creator.name) {
                                chat.iconName = chat.creator.name.substr(chat.creator.name.length - 1).toUpperCase();
                            }
                            var d = new Date(chat.createDate);
                            chat.createDateFormat = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                        });
                        $("#chatSearchTpl").tmpl(chats).appendTo($pp.children('.ui.list').empty());
                        $('.pp-chat-search-results .timeago').timeago();

                    } else {
                        toastr.error(data.data, "加载失败!");
                    }
                });
            }
        }).click(function(event) {
            var $input = $('.chat-search .ui.search input');
            if (!$input.val()) {
                $input.focus();
            }
        });

        $('.chat-search .ui.search input').keyup(function(event) {
            if (event.keyCode == 13) {
                searchHandler();
            }
        });

        // 检索结果 | @消息 | 收藏消息 条目点击处理
        $('.list-chat-search-results, .pp-ats-content, .pp-stows-content').on('click', '.item', function(event) {
            event.preventDefault();
            event.stopImmediatePropagation();
            $item = $(this);
            $.get('/admin/chat/searchBy', {
                id: $item.attr('data-id')
            }, function(data) {
                if (data.success) {

                    if ($item.attr('data-type') == 'at') { // mark chatAt as readed.
                        $.post('/admin/chat/markAsReaded/unmask', {
                            chatAtId: $item.attr('data-chat-at-id')
                        }, function(data, textStatus, xhr) {
                            if (data.success) {
                                window.poll.reset();
                            } else {
                                toastr.error(data.data, "错误提示!");
                            }
                        });
                    }

                    var chats = data.data.content;
                    if (chats.length == 0) {
                        toastr.error("检索结果不存在!");
                        return;
                    }

                    var $btnUp = $('.chat .btn-chat-more');
                    var $btnDown = $('.chat .btn-chat-pre-more');

                    if (data.data.last) {
                        $btnUp.remove();
                        $btnUp = $('.chat .btn-chat-more');
                    } else {
                        if ($btnUp.size() == 0) {
                            $btnUp = $('<button class="fluid ui basic button btn-chat-more">加载更多</button>')
                                .text('加载更多(' + (data.data.totalElements - (data.data.number + 1) * data.data.size) + ')');
                            $btnUp.insertAfter('.chat .comments > h3');
                        } else {
                            $btnUp.text('加载更多(' + (data.data.totalElements - (data.data.number + 1) * data.data.size) + ')');
                        }

                        $('input:hidden[name="page.number.next"]').val(data.data.number + 1);
                    }

                    if (data.data.first) {
                        $btnDown.remove();
                        $btnDown = $('.chat .btn-chat-pre-more');
                    } else {
                        if ($btnDown.size() == 0) {
                            $btnDown = $('<button class="fluid ui basic button btn-chat-pre-more">加载更多</button>')
                                .text('加载更多(' + (data.data.number * data.data.size) + ')');
                            $btnDown.insertBefore('.chat .fm-reply')
                        } else {
                            $btnDown.text('加载更多(' + (data.data.number * data.data.size) + ')');
                        }
                        $('input:hidden[name="page.number.pre"]').val(data.data.number - 1);
                    }

                    $('.chat .comments .comment').remove();

                    $after = $btnUp.size() == 0 ? $('.chat .comments > h3') : $btnUp;

                    var $more = convertChat(chats, $item.attr('data-id'));
                    $more.insertAfter($after);

                    jQuery(".timeago").timeago();

                    s2m();
                }
            });
        });

        // 收藏 消息 移除处理
        $('.pp-stows-content').on('click', '.item .actions .remove', function(event) {
            event.preventDefault();
            event.stopImmediatePropagation();
            $item = $(this).closest('.item');

            $.post('/admin/chat/removeStow/unmask', {
                id: $item.attr('data-chat-stow-id')
            }, function(data, textStatus, xhr) {
                if (data.success) {
                    $item.remove();
                    toastr.success('移除收藏成功!');
                } else {
                    toastr.error(data.data, '移除收藏失败!');
                }
            });

        });

        // @消息 知悉 处理
        $('.pp-ats-content').on('click', '.item .actions .markAsRead', function(event) {
            event.preventDefault();
            event.stopImmediatePropagation();
            $item = $(this).closest('.item');

            $.post('/admin/chat/markAsReaded/unmask', {
                chatAtId: $item.attr('data-chat-at-id')
            }, function(data, textStatus, xhr) {
                if (data.success) {
                    $item.remove();
                    window.poll.reset();
                } else {
                    toastr.error(data.data, "知悉@消息失败!");
                }
            });

        });

        // @消息 全部知悉 处理
        $('.pp-ats .pp-ats-remove').on('click', function(event) {
            event.preventDefault();
            event.stopImmediatePropagation();

            $.post('/admin/chat/markAllAsReaded/unmask',
                function(data, textStatus, xhr) {
                    if (data.success) {
                        $('.pp-ats-content .ui.list').empty();
                        window.poll.reset();
                    } else {
                        toastr.error(data.data, "知悉全部@消息失败!");
                    }
                });

        });

        // ------------------------------------------------------------------------------------- chat search end

        $('table').tablesort().data('tablesort');
        // $('.ui.dropdown').dropdown();
        $('.ui.dropdown.dd-more-actions').dropdown({
            action: 'hide',
            direction: 'downward'
        });
        $('.ui.dropdown.dd-quick-reply').dropdown({
            action: 'hide',
            direction: 'downward'
        });
        $('.ui.dropdown.dd-labels').dropdown({
            allowAdditions: true,
            forceSelection: false
        });
        $('.pp').popup();
        $('.pp-users.field,.pp-edit-users.field').popup({
            inline: true,
            hoverable: true,
            position: 'bottom left',
            distanceAway: -10,
            on: 'manual',
            observeChanges: false,
            delay: {
                show: 300,
                hide: 800
            }
        });

        // 是否第一次调用s2b函数
        var isS2bFirst = true;

        $('.list-users-container .list-users').on('click', '.item', function(event) {
            addAtUser(cm, $('.pp-users'), $(this));
        });
        $('.list-edit-users-container .list-users').on('click', '.item', function(event) {
            addAtUser(cme, $('.pp-edit-users'), $(this));
        });

        /**
         * 解析@users
         * @param  {[type]} plainText [description]
         * @return {[type]}           [description]
         */
        function parseUsers(plainText) {
            var users = [];
            var atR = /\{~([^\}]*)\}/g;
            var rs = atR.exec(plainText);
            while (rs) {
                if (userMap[rs[1]] && users.indexOf(rs[1]) == -1) {
                    users.push(rs[1]);
                }
                rs = atR.exec(plainText);
            }

            return users;
        }

        /**
         * 解析@groups
         * @param  {[type]} plainText [description]
         * @return {[type]}           [description]
         */
        function parseGroups(plainText) {
            var groups = [];
            var atR = /\{!~([^\}]*)\}/g;
            var rs = atR.exec(plainText);
            while (rs) {
                if (userMap[rs[1]] && groups.indexOf(rs[1]) == -1) {
                    groups.push(rs[1]);
                }
                rs = atR.exec(plainText);
            }

            return groups;
        }

        /**
         * 解析要发送邮件的用户们
         * @param  {[type]} plainText [description]
         * @return {[type]}           [description]
         */
        function parseUsernames(plainText) {
            var users = parseUsers(plainText);
            if (users.indexOf('all') > -1) {
                return usernameAll;
            }
            return users;
        }

        /**
         * 解析要发送邮件的用户组们
         * @param  {[type]} plainText [description]
         * @return {[type]}           [description]
         */
        function parseGroupNames(plainText) {
            var groupNameArr = [];
            var groups = parseGroups(plainText);
            $.each(groups, function(index, group) {
                if (groupNameArr.indexOf(group) == -1) {
                    groupNameArr.push(group);
                }
            });
            return groupNameArr;
        }
        /**
         * 替换@user解析
         * @param  {[type]} plainText [description]
         * @return {[type]}           [description]
         */
        function preParse(plainText) {

            var txt = plainText;
            $.each(parseUsers(plainText), function(index, username) {
                txt = txt.replace(new RegExp('{~' + username + '}', 'g'), '<span data-value="' + username + '" class="at-user">' + '**`@' + userMap[username] + '`**' + '</span>');
            });
            $.each(parseGroups(plainText), function(index, groupName) {
                txt = txt.replace(new RegExp('{!~' + groupName + '}', 'g'), '<span data-value="' + groupName + '" class="at-group">' + '**`@' + userMap[groupName] + '(组)`**' + '</span>');
            });

            return txt;
        }

        var simplemdeEdit = initIDE($(".ad-chat-edit textarea")[0], "chat-edit-content");
        var simplemde = initIDE($(".ta-md")[0], "chat-content");
        var cm = simplemde.codemirror;
        var cme = simplemdeEdit.codemirror;

        // 注册全局markdown解析函数
        window.parseMd = function(contentMd) {
            return simplemde.markdown(preParse(contentMd));
        }

        /**
         * 出事markdown ide
         * @param  {[type]} $elem [description]
         * @return {[type]}       [description]
         */
        function initIDE($elem, uniqueId) {
            var mde = new SimpleMDE({
                element: $elem,
                autoDownloadFontAwesome: false,
                autofocus: true,
                spellChecker: false,
                status: false,
                toolbar: [
                    "bold",
                    "italic",
                    "strikethrough",
                    "heading-smaller",
                    "heading-bigger",
                    "|",
                    "code",
                    "quote",
                    "unordered-list",
                    "ordered-list", {
                        name: "tasks",
                        action: function(editor) {
                            insertComment(editor.codemirror, '- [ ] 未完成任务\n- [x] 已完成任务');
                        },
                        className: "fa fa-check-square-o ",
                        title: "任务列表",
                    }, {
                        name: "details",
                        action: function(editor) {
                            insertComment(editor.codemirror, '<details>\n<summary>标题</summary>\n<p>详情内容</p>\n</details>');
                        },
                        className: "fa fa-play ",
                        title: "折叠详情",
                    },
                    "|",
                    "link",
                    "image",
                    "table",
                    "horizontal-rule",
                    "|", {
                        name: "upload",
                        action: function(editor) {},
                        className: "fa fa-upload",
                        title: "上传文件",
                    }, {
                        name: "emoji",
                        action: function(editor) {},
                        className: "fa fa-smile-o ",
                        title: "Emoji表情",
                    }, "|",
                    "preview",
                    "side-by-side",
                    "fullscreen"
                    // "guide"

                ],
                insertTexts: {
                    table: ["", "\n\n| 列1 | 列2 | 列3 |\n| ------ | ------ | ------ |\n| 文本 | 文本 | 文本 |\n\n"],
                },
                renderingConfig: {
                    codeSyntaxHighlighting: true,
                },
                previewRender: function(plainText, preview) { // Async method
                    return mde.markdown(preParse(plainText));
                },
                autosave: {
                    enabled: true,
                    delay: 5000,
                    uniqueId: uniqueId
                }
            });

            return mde;
        }

        // TODO simplemde edit also keyup
        simplemde.codemirror.on('keyup', function(cm, e) {
            if (e.ctrlKey && e.keyCode == 13) { // Ctrl+Enter
                if (!$('.btn-chat-submit').hasClass('disabled')) {
                    $('.btn-chat-submit').click();
                }
            } else if (e.keyCode == 27) { // Esc
                $('.btn-chat-clear').click();
            }
        });
        simplemdeEdit.codemirror.on('keyup', function(cm, e) {
            if (e.ctrlKey && e.keyCode == 13) { // Ctrl+Enter
                $('.ad-chat-edit .btn-chat-edit-submit').click();
            } else if (e.keyCode == 27) { // Esc
                $('.ad-chat-edit .btn-chat-edit-clear').click();
            }
        });

        initUploadPp4IDE($('.fm-reply .editor-toolbar a.fa-upload'), $('.pp-chat-upload-file'));
        initUploadPp4IDE($('.fm-edit-reply .editor-toolbar a.fa-upload'), $('.pp-chat-edit-upload-file'));

        initEmojiPp4IDE($('.fm-reply .editor-toolbar a.fa-smile-o'), $('.pp-chat-emoji'), cm);
        initEmojiPp4IDE($('.fm-edit-reply .editor-toolbar a.fa-smile-o'), $('.pp-chat-edit-emoji'), cme);

        initDropzone4IDE($(".pp-chat-upload-file form.dropzone"), cm);
        initDropzone4IDE($(".pp-chat-edit-upload-file form.dropzone"), cme);

        initDropzone4IDE($(".fm-reply .CodeMirror-wrap"), cm, true);
        initDropzone4IDE($(".fm-edit-reply .CodeMirror-wrap"), cme, true);


        /**
         * 初始化上传区域弹出框
         * @param  {[type]} $ppTarget [description]
         * @param  {[type]} $pp       [description]
         * @return {[type]}           [description]
         */
        function initUploadPp4IDE($ppTarget, $pp) {
            $ppTarget.popup({
                popup: $pp,
                hoverable: true,
                on: 'click',
                position: 'bottom right',
                closable: false,
                delay: {
                    show: 300,
                    hide: 300
                },
                onShow: function() {}
            });
        }

        /**
         * 初始化上传区域弹出框
         * @param  {[type]} $ppTarget [description]
         * @param  {[type]} $pp       [description]
         * @return {[type]}           [description]
         */
        function initEmojiPp4IDE($ppTarget, $pp, _cm) {
            $ppTarget.popup({
                popup: $pp,
                hoverable: true,
                on: 'click',
                position: 'bottom right',
                closable: false,
                delay: {
                    show: 300,
                    hide: 300
                },
                onShow: function() {
                    emoji.init($pp, _cm);
                }
            });
        }

        /**
        /**
         * 初始化上传组件
         * @param  {[type]} $dz [description]
         * @param  {[type]} cm  [description]
         * @param  {[type]} nonForm  [description]
         * @return {[type]}     [description]
         */
        function initDropzone4IDE($dz, cm, nonForm) {
            $dz.dropzone({
                url: "/admin/file/upload",
                paramName: 'file',
                clickable: !nonForm,
                dictDefaultMessage: '拖拽或点击上传',
                init: function() {
                    this.on("sending", function(file, xhr, formData) {
                        // Will send the filesize along with the file as POST data.
                        nonForm && formData.append($('.ad-csrf input:hidden').attr('name'), $('.ad-csrf input:hidden').attr('value'));
                    });
                    this.on("success", function(file, data) {
                        if (data.success) {

                            $.each(data.data, function(index, item) {
                                if (item.type == 'Image') {
                                    insertComment(cm, '![{name}]({baseURL}{path}{uuidName}) '
                                        .replace(/\{name\}/g, item.name)
                                        .replace(/\{baseURL\}/g, baseURL)
                                        .replace(/\{path\}/g, item.path)
                                        .replace(/\{uuidName\}/g, item.uuidName));
                                } else {
                                    insertComment(cm, '[{name}]({baseURL}{path}{uuidName}) '
                                        .replace(/\{name\}/g, item.name)
                                        .replace(/\{baseURL\}/g, baseURL)
                                        .replace(/\{path\}/g, "admin/file/download/")
                                        .replace(/\{uuidName\}/g, item.id));
                                }
                            });
                            toastr.success('上传成功!');
                        } else {
                            toastr.error(data.data, '上传失败!');
                        }

                    });
                    this.on("error", function(file, errorMessage, xhr) {
                        toastr.error(errorMessage, '上传失败!');
                    });
                    this.on("complete", function(file) {
                        this.removeFile(file);
                    });
                }
            });
        }

        // ============================================================================ @user start
        // TODO 临时全局变量定义
        var mk = ' @';
        var usernames = []; // 用户名&用户组
        var usernameAll = []; // 用户名
        var userMap = {};
        $('.list-users-container .list-users > .item').each(function(index, el) {
            var value = $(el).attr('data-value');
            usernames.push(value);
            userMap[value] = $(el).attr('data-label');
            if ($(el).attr('data-type') != 'group' && value != 'all') {
                usernameAll.push(value);
            }
        });

        function atUserHandler($pp, $usersContainer) {

            return function(cm, o) {

                var cursor = cm.getCursor();
                var line = cm.getLine(cursor.line);

                var indexAt = line.lastIndexOf('@');
                if (indexAt == 0) {
                    mk = '@';
                } else if (indexAt > 0) {
                    mk = ' @';
                } else {
                    $pp.popup('is visible') && $pp.popup('hide');
                    return;
                }

                var mkIndex = line.lastIndexOf(mk);
                var atFrom = mkIndex + mk.length;
                if (mkIndex > -1 && cursor.ch >= atFrom) {

                    $pp.popup('is hidden') && $pp.popup('show');

                    // var at = $.trim(line.substr(atFrom).split(' ')[0]);
                    var at = $.trim(line.substring(atFrom, cursor.ch).split(' ')[0]);

                    if (at) {
                        $.each(usernames, function(index, username) {
                            if (username.indexOf(at) == -1) {
                                $usersContainer.find('.list-users > .item[data-value="' + username + '"]').hide();
                            } else {
                                $usersContainer.find('.list-users > .item[data-value="' + username + '"]').show();
                            }
                        });
                    } else {
                        $('.list-users > .item').each(function(index, el) {
                            $(el).show();
                        });
                    }

                    var $s = $usersContainer.find('.list-users > .item:visible').each(function(index, el) {
                        $(el).removeClass('active');
                    }).first().addClass('active');
                    $usersContainer.scrollTo($s);

                } else {
                    $pp.popup('is visible') && $pp.popup('hide');
                }

            };
        }

        cm.on('cursorActivity', atUserHandler($('.pp-users'), $('.list-users-container')));
        cme.on('cursorActivity', atUserHandler($('.pp-edit-users'), $('.list-edit-users-container')));

        function atUserKDHandler($pp, $usersContainer) {

            return function(cm, e) {

                if ((e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 13) && $pp.popup('is visible')) {

                    var cnt = $usersContainer.find('.list-users > .item:visible').size();
                    if (cnt == 0) {
                        return;
                    }
                    var $selected = $usersContainer.find('.list-users > .active.item:visible');
                    var selectIndex = $usersContainer.find('.list-users > .item:visible').index($selected); //$selected.index('.list-users > .item:visible');
                    var nextIndex = (selectIndex + 1 + cnt) % cnt;
                    var preIndex = (selectIndex - 1 + cnt) % cnt;
                    if (e.keyCode == 38) { // key up
                        e.preventDefault();
                        var $s = $usersContainer.find('.list-users > .item:visible').each(function(index, el) {
                            $(el).removeClass('active');
                        }).eq(preIndex).addClass('active');
                        $usersContainer.scrollTo($s);
                    } else if (e.keyCode == 40) { // key down
                        e.preventDefault();
                        var $s = $usersContainer.find('.list-users > .item:visible').each(function(index, el) {
                            $(el).removeClass('active');
                        }).eq(nextIndex).addClass('active');
                        $usersContainer.scrollTo($s);
                    } else if (e.keyCode == 13) { // key enter
                        e.preventDefault();
                        addAtUser(cm, $pp, $selected);
                    }
                }

            };
        }

        cm.on('keydown', atUserKDHandler($('.pp-users'), $('.list-users-container')));
        cme.on('keydown', atUserKDHandler($('.pp-edit-users'), $('.list-edit-users-container')));

        /**
         * 添加转换选择的@user到编辑器
         * @param {CodeMirror} cm CodeMirror
         */
        function addAtUser(cm, $pp, $user) {
            var cursor = cm.getCursor();
            var line = cm.getLine(cursor.line);
            var mkIndex = line.lastIndexOf(mk);
            var atFrom = mkIndex + mk.length;
            if (mkIndex > -1 && cursor.ch >= atFrom) {

                var type = $user.attr('data-type');
                var showTxt = (type == 'group') ? '{!~' + $user.attr('data-value') + '}' : '{~' + $user.attr('data-value') + '}';

                cm.replaceRange(showTxt, {
                    line: cursor.line,
                    ch: atFrom - 1
                }, {
                    line: cursor.line,
                    ch: cursor.ch
                });
            }

            $pp.popup('is visible') && $pp.popup('hide');

            cm.focus();
        }

        function insertAtUserOrGroup(cm, username, isGroup) {
            var cursor = cm.getCursor();
            if (cursor) {
                if (!isGroup) {
                    cm.replaceRange('{~' + username + '}', cursor, cursor);
                } else {
                    cm.replaceRange('{!~' + username + '}', cursor, cursor);
                }

            }
        }

        /**
         * 编辑器插入自定义沟通内容
         * @param  {[type]} cm      [description]
         * @param  {[type]} comment [description]
         * @return {[type]}         [description]
         */
        function insertComment(cm, comment) {
            var cursor = cm.getCursor();
            if (cursor) {
                cm.replaceRange(comment, cursor, cursor);

                s2b();
                cm.focus();
            }
        }

        // ============================================================================ @user end

        // ============================================================================ @chat markdown to html start

        var $textMds = $('.comments .content .text.markdown-body');
        $textMds.each(function(index, el) {
            var html = simplemde.markdown(preParse($(el).attr('data-content')));
            $(el).html(html);
        });

        $('.ui.comments').show();

        // ============================================================================ @chat markdown to html end

        // -------------------------------------------------------------------------------- sticky init start
        $('.main.container .right.rail .sticky').css('max-height', $(window).height() - 70);
        // $('.ad-index-container .left.rail.ad-index-rail .sticky').css('max-height', $(window).height() - 70);
        $(window).resize(function(event) {
            $('.main.container .right.rail .sticky').css('max-height', $(window).height() - 70);
            // $('.ad-index-container .left.rail.ad-index-rail .sticky').css('max-height', $(window).height() - 70);
        });
        if ($('.main.container .right.rail').is(':visible')) {
            $('.ui.sticky.sy-dynamic').sticky({
                offset: 70,
                observeChanges: true,
                context: '#context'
            });
        }
        // -------------------------------------------------------------------------------- sticky init end

        // ============================================================================ url? start

        // 替换浏览器url地址,去掉查询参数.
        function replaceHistory() {
            if ('pushState' in history) {
                history.replaceState(null, '', url('path') + '?scroll=1');
                Utils.remember();
                var dynamicUrl = Utils.getRemember('/admin/dynamic');
                dynamicUrl && $('a.item.mi-dynamic').attr('href', dynamicUrl);
            }
        }

        if (url('?scroll') || url('?scroll') == '') {
            s2b();
            cm.focus();
        }

        if (url('?id')) {
            s2m(); // 滚动到标记沟通消息处
            replaceHistory();
        }

        if (url('?at')) {

            simplemde.value(''); // 首先清空编辑器
            var atArr = url('?at').split(',');

            var ats = [];
            $.each(atArr, function(index, at) {
                var _at = '{~{username}}'.replace(/\{username\}/g, at);
                if (ats.indexOf(_at) == -1) {
                    ats.push(_at);
                }
            });
            // [[翻译#173](/admin/dynamic?id=173){~admin} & {~step}]
            // var comment = '### 沟通讨论([翻译#{translateId}](admin/translate?id={translateId}))\n---\n{ats} ';
            var comment = '[[翻译#{translateId}]({baseURL}admin/translate?id={translateId}){ats}]\n\n';
            comment = comment.replace(/\{translateId\}/g, url('?translateId'))
                .replace(/\{baseURL\}/g, baseURL)
                .replace(/\{ats\}/g, ats.join(' & '));
            insertComment(cm, comment);

            replaceHistory();
        }

        // ============================================================================ url? end

        $('.btn-scroll-up').click(function(event) {
            s2t();
        });

        $('.btn-scroll-down').click(function(event) {
            s2b();
        });

        // 滚动到标记处
        function s2m() {

            Utils.imgLoaded($('.chat .ui.comments .comment .text img'), function() {
                $('html, body, .ad-index-content').scrollTo($(".comments .comment.marked"), 300, {
                    offset: -50
                });

                if ($('.main.container .right.rail').is(':visible')) {
                    $('.ui.sticky').sticky('refresh');
                }
            });
        }

        // 滚动到顶部
        function s2t() {
            $('html, body, .ad-index-content').scrollTo(0, 300);
        }

        // 滚动到标记处
        function s2mk($p, offset) {

            Utils.imgLoaded($('.chat .ui.comments .comment .text img'), function() {
                $('html, body, .ad-index-content').scrollTo($p ? $p : $(".marker").first().removeClass('marker'), 300, {
                    offset: offset ? offset : -50
                });
            });
        }

        // 滚动到底部
        function s2b() {

            if (isS2bFirst) { // 解决页面首次加载, 有图片加载比较慢导致没有滚动到顶部问题.
                isS2bFirst = false;
                Utils.imgLoaded($('.chat .ui.comments .comment .text img'), function() {
                    $('html, body, .ad-index-content').scrollTo({
                        left: 0,
                        top: "100%"
                    }, 300);
                    if ($('.main.container .right.rail').is(':visible')) {
                        $('.ui.sticky').sticky('refresh');
                    }

                });
            } else {
                $('html, body, .ad-index-content').scrollTo({
                    left: 0,
                    top: "100%"
                }, 300);
                if ($('.main.container .right.rail').is(':visible')) {
                    $('.ui.sticky').sticky('refresh');
                }
            }
        }

        /**
         * chat 内容转换
         * @param  {[type]} chats 沟通消息数组
         * @return {[type]}       返回模板编译后的jquery dom
         */
        function convertChat(chats, markId, first) {
            var isAdminRole = $('input:hidden[name="role.admin"]').val();
            var isSuperRole = $('input:hidden[name="role.super"]').val();
            var loginUsername = $('input:hidden[name="user.username"]').val();
            $.each(chats, function(index, chat) {
                chat.contentMd = simplemde.markdown(preParse(chat.content));
                chat.marked = (chat.id == markId) ? 'marked' : '';
                chat.marker = (first === true && (index == 0)) ? 'marker' : ((first === false && (index == chats.length - 1)) ? 'marker' : '');
                chat.zanCount = (chat.voteZan) ? chat.voteZan.split(',').length : 0;
                chat.caiCount = (chat.voteCai) ? chat.voteCai.split(',').length : 0;
                chat.textShare = baseURL + 'admin/dynamic?id=' + chat.id;
                chat.isNotWiki = (chat.type != "Wiki");
                if (chat.creator.name) {
                    chat.creator.iconName = chat.creator.name.substr(chat.creator.name.length - 1).toUpperCase();
                }

                chat.isOpenEdit = !!chat.openEdit;
                chat.openEditText = chat.isOpenEdit ? '关闭协作' : '开启协作';

                if (isAdminRole == 'true' || loginUsername == chat.creator.username) {
                    chat.isWikiable = chat.isNotWiki;
                }
                if (isSuperRole == 'true' || loginUsername == chat.creator.username) {
                    chat.actions = true;
                }
                if (isSuperRole == 'true' || loginUsername == chat.creator.username || chat.isOpenEdit) {
                    chat.isEditable = true;
                }
                var d = new Date(chat.createDate);
                chat.createDateFormat = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
            });
            var $more = $("#chatMoreTpl").tmpl(chats);
            $more.find('.ui.dropdown.dd-more-actions').dropdown({
                action: 'hide',
                direction: 'downward'
            });
            $more.find('.ui.dropdown.dd-quick-reply').dropdown({
                action: 'hide',
                direction: 'downward'
            });

            return $more;
        }

        $('.btn-chat-submit').click(function(event) {
            event.preventDefault();

            $btn = $(this);

            var content = simplemde.value();
            if (!$.trim(content)) {
                toastr.error('提交内容不能为空!');
                return;
            }

            if (isFetchNews) {
                toastr.warning('自动刷新沟通消息中,请稍后再尝试...');
                return;
            }

            var html = $('<div class="markdown-body"/>').html('<style>.markdown-body{font-size:14px;line-height:1.6}.markdown-body>:first-child{margin-top:0!important}.markdown-body>:last-child{margin-bottom:0!important}.markdown-body a.absent{color:#C00}.markdown-body a.anchor{bottom:0;cursor:pointer;display:block;left:0;margin-left:-30px;padding-left:30px;position:absolute;top:0}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6{cursor:text;font-weight:700;margin:20px 0 10px;padding:0;position:relative}.markdown-body h1 .mini-icon-link,.markdown-body h2 .mini-icon-link,.markdown-body h3 .mini-icon-link,.markdown-body h4 .mini-icon-link,.markdown-body h5 .mini-icon-link,.markdown-body h6 .mini-icon-link{color:#000;display:none}.markdown-body h1:hover a.anchor,.markdown-body h2:hover a.anchor,.markdown-body h3:hover a.anchor,.markdown-body h4:hover a.anchor,.markdown-body h5:hover a.anchor,.markdown-body h6:hover a.anchor{line-height:1;margin-left:-22px;padding-left:0;text-decoration:none;top:15%}.markdown-body h1:hover a.anchor .mini-icon-link,.markdown-body h2:hover a.anchor .mini-icon-link,.markdown-body h3:hover a.anchor .mini-icon-link,.markdown-body h4:hover a.anchor .mini-icon-link,.markdown-body h5:hover a.anchor .mini-icon-link,.markdown-body h6:hover a.anchor .mini-icon-link{display:inline-block}.markdown-body hr:after,.markdown-body hr:before{display:table;content:""}.markdown-body h1 code,.markdown-body h1 tt,.markdown-body h2 code,.markdown-body h2 tt,.markdown-body h3 code,.markdown-body h3 tt,.markdown-body h4 code,.markdown-body h4 tt,.markdown-body h5 code,.markdown-body h5 tt,.markdown-body h6 code,.markdown-body h6 tt{font-size:inherit}.markdown-body h1{color:#000;font-size:28px}.markdown-body h2{border-bottom:1px solid #CCC;color:#000;font-size:24px}.markdown-body h3{font-size:18px}.markdown-body h4{font-size:16px}.markdown-body h5{font-size:14px}.markdown-body h6{color:#777;font-size:14px}.markdown-body blockquote,.markdown-body dl,.markdown-body ol,.markdown-body p,.markdown-body pre,.markdown-body table,.markdown-body ul{margin:15px 0}.markdown-body hr{overflow:hidden;background:#e7e7e7;height:4px;padding:0;margin:16px 0;border:0;-moz-box-sizing:content-box;box-sizing:content-box}.markdown-body h1+p,.markdown-body h2+p,.markdown-body h3+p,.markdown-body h4+p,.markdown-body h5+p,.markdown-body h6+p,.markdown-body ol li>:first-child,.markdown-body ul li>:first-child{margin-top:0}.markdown-body hr:after{clear:both}.markdown-body a:first-child h1,.markdown-body a:first-child h2,.markdown-body a:first-child h3,.markdown-body a:first-child h4,.markdown-body a:first-child h5,.markdown-body a:first-child h6,.markdown-body>h1:first-child,.markdown-body>h1:first-child+h2,.markdown-body>h2:first-child,.markdown-body>h3:first-child,.markdown-body>h4:first-child,.markdown-body>h5:first-child,.markdown-body>h6:first-child{margin-top:0;padding-top:0}.markdown-body li p.first{display:inline-block}.markdown-body ol,.markdown-body ul{padding-left:30px}.markdown-body ol.no-list,.markdown-body ul.no-list{list-style-type:none;padding:0}.markdown-body ol ol,.markdown-body ol ul,.markdown-body ul ol,.markdown-body ul ul{margin-bottom:0}.markdown-body dl{padding:0}.markdown-body dl dt{font-size:14px;font-style:italic;font-weight:700;margin:15px 0 5px;padding:0}.markdown-body dl dt:first-child{padding:0}.markdown-body dl dt>:first-child{margin-top:0}.markdown-body dl dt>:last-child{margin-bottom:0}.markdown-body dl dd{margin:0 0 15px;padding:0 15px}.markdown-body blockquote>:first-child,.markdown-body dl dd>:first-child{margin-top:0}.markdown-body blockquote>:last-child,.markdown-body dl dd>:last-child{margin-bottom:0}.markdown-body blockquote{border-left:4px solid #DDD;color:#777;padding:0 15px}.markdown-body table th{font-weight:700}.markdown-body table td,.markdown-body table th{border:1px solid #CCC;padding:6px 13px}.markdown-body table tr{background-color:#FFF;border-top:1px solid #CCC}.markdown-body table tr:nth-child(2n){background-color:#F8F8F8}.markdown-body img{max-width:100%}.markdown-body span.frame{display:block;overflow:hidden}.markdown-body span.frame>span{border:1px solid #DDD;display:block;float:left;margin:13px 0 0;overflow:hidden;padding:7px;width:auto}.markdown-body span.frame span img{display:block;float:left}.markdown-body span.frame span span{clear:both;color:#333;display:block;padding:5px 0 0}.markdown-body span.align-center{clear:both;display:block;overflow:hidden}.markdown-body span.align-center>span{display:block;margin:13px auto 0;overflow:hidden;text-align:center}.markdown-body span.align-center span img{margin:0 auto;text-align:center}.markdown-body span.align-right{clear:both;display:block;overflow:hidden}.markdown-body span.align-right>span{display:block;margin:13px 0 0;overflow:hidden;text-align:right}.markdown-body span.align-right span img{margin:0;text-align:right}.markdown-body span.float-left{display:block;float:left;margin-right:13px;overflow:hidden}.markdown-body span.float-left span{margin:13px 0 0}.markdown-body span.float-right{display:block;float:right;margin-left:13px;overflow:hidden}.markdown-body span.float-right>span{display:block;margin:13px auto 0;overflow:hidden;text-align:right}.markdown-body code,.markdown-body tt{background-color:#F8F8F8;border:1px solid #EAEAEA;border-radius:3px;margin:0 2px;padding:0 5px;white-space:nowrap}.markdown-body pre>code{background:none;border:none;margin:0;padding:0;white-space:pre}.markdown-body .highlight pre,.markdown-body pre{background-color:#F8F8F8;border:1px solid #CCC;border-radius:3px;font-size:13px;line-height:19px;overflow:auto;padding:6px 10px}.markdown-body pre code,.markdown-body pre tt{background-color:transparent;border:none}</style>' + simplemde.markdown(preParse(content))).wrap('<div/>').parent().html();

            var preMore = $('.btn-chat-pre-more').size() == 1;
            var $last = $('.chat .comments .comment').last();

            var $domBefore = preMore ? $('.btn-chat-pre-more') : $('.fm-reply');

            window.poll.pause(); // 因为提交消息,会顺便拉取新消息, 所以暂停轮询

            $btn.addClass('disabled');

            $.post('/admin/chat/create', {
                preMore: preMore,
                lastId: $last.size() == 0 ? -1 : $('.chat .comments .comment').last().attr('data-id'),
                baseURL: baseURL,
                usernames: parseUsernames(content).join(','),
                groups: parseGroupNames(content).join(','),
                content: content,
                contentHtml: html,
            }, function(data, textStatus, xhr) {
                if (data.success) {

                    simplemde.value('');
                    simplemde.autosave();

                    if (simplemde.isPreviewActive()) {
                        $('.fm-reply .editor-toolbar a.fa.fa-eye').click();
                    }
                    if (simplemde.isFullscreenActive()) {
                        $('.fm-reply .editor-toolbar a.fa.fa-arrows-alt').click();
                    }

                    toastr.success('提交成功!');

                    $('.btn-get-chat-news').hide(); // 已经顺便拉取了更新,所以隐藏获取更新按钮

                    if ($.isArray(data.data)) { // 不刷新追加
                        if (data.data.length == 0) {
                            return;
                        }

                        var $more = convertChat(data.data, null, null);
                        $more.insertBefore($domBefore);
                        jQuery(".timeago").timeago();
                        s2b();
                    } else {
                        window.location.href = url('path') + '?scroll=1';
                    }

                } else {
                    toastr.error(data.data, '提交失败!');
                }
            }).always(function() {
                window.poll.reset(); // 重置轮询频率
                $btn.removeClass('disabled');
            });
        });

        $('.btn-chat-clear').click(function(event) {
            event.preventDefault();
            simplemde.clearAutosavedValue();
            simplemde.value('');
            simplemde.autosave();

            if (simplemde.isPreviewActive()) {
                $('.fm-reply .editor-toolbar a.fa.fa-eye').click();
            }
            if (simplemde.isFullscreenActive()) {
                $('.fm-reply .editor-toolbar a.fa.fa-arrows-alt').click();
            }

            record.back();
        });

        // 用户停留视图位置记录
        var record = (function() {

            var _$p = null; // 位置记录点

            return {
                mark: function($p) {
                    _$p = $p;
                },
                back: function() {
                    this.exist() && s2mk(_$p);
                    this.reset();
                },
                reset: function() {
                    _$p = null;
                },
                exist: function() {
                    return (_$p != null);
                }
            };
        })();

        // 消息回复点击处理
        $('body').on('click', '.comments .actions a.reply', function(event) {
            event.preventDefault();
            $btn = $(this);
            var id = $btn.closest('.comment').attr('data-id');
            var username = $btn.closest('.comment').find('.content .author').attr('data-value');

            record.mark($btn.closest('.comment'));

            // [[回复#10](admin/dynamic?id=1){~xiweicheng}]
            var comment = '[[回复#{id}]({baseURL}admin/dynamic?id={id}){~{username}}]\n\n';
            comment = comment.replace(/\{id\}/g, id)
                .replace(/\{baseURL\}/g, baseURL)
                .replace(/\{username\}/g, username);
            insertComment(cm, comment);

            // 标记对应消息@到自己的消息为已读
            $.post('/admin/chat/markAsReadedByChat/unmask', {
                chatId: id
            });

        });

        $('body').on('click', '.comments .actions a.stow', function(event) {
            event.preventDefault();
            $btn = $(this);

            $.post('/admin/chat/stow/unmask', {
                id: $btn.closest('.comment').attr('data-id')
            }, function(data, textStatus, xhr) {
                if (data.success) {
                    toastr.success('收藏成功!');
                } else {
                    toastr.error(data.data, '收藏失败!');
                }
            });

        });

        $('body').on('click', '.comments .actions .delete', function(event) {
            $btn = $(this);
            $('.ad-delete-confirm').modal({
                onApprove: function() {
                    $.post('/admin/chat/delete', {
                        id: $btn.closest('.comment').attr('data-id')
                    }, function(data, textStatus, xhr) {
                        if (data.success) {
                            $btn.closest('.comment').remove();
                            toastr.success('删除成功!');
                        } else {
                            toastr.error(data.data, '删除失败!');
                        }
                    });
                }
            }).modal('show');
        });

        $('body').on('click', '.comments .actions .edit', function(event) {
            $btn = $(this);

            $.get('/admin/chat/get', {
                id: $btn.closest('.comment').attr('data-id')
            }, function(data) {
                if (data.success) {

                    var contentOld = data.data.content;

                    $('.ad-chat-edit').modal({
                        autofocus: false,
                        observeChanges: true,
                        closable: false, // 防止修改内容没保存窗口关闭导致数据丢失
                        onVisible: function() {
                            simplemdeEdit.codemirror.focus();
                            simplemdeEdit.value(contentOld);
                        },
                        onApprove: function() {
                            if (!simplemdeEdit.value()) {
                                toastr.error('更新内容不能为空!');
                                return false;
                            }

                            var content = simplemdeEdit.value();
                            if (contentOld == content) {
                                toastr.error('修改内容没有任何变更的内容!');
                                return false;
                            }

                            var htmlOld = $('<div class="markdown-body"/>').html('<style>.markdown-body{font-size:14px;line-height:1.6}.markdown-body>:first-child{margin-top:0!important}.markdown-body>:last-child{margin-bottom:0!important}.markdown-body a.absent{color:#C00}.markdown-body a.anchor{bottom:0;cursor:pointer;display:block;left:0;margin-left:-30px;padding-left:30px;position:absolute;top:0}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6{cursor:text;font-weight:700;margin:20px 0 10px;padding:0;position:relative}.markdown-body h1 .mini-icon-link,.markdown-body h2 .mini-icon-link,.markdown-body h3 .mini-icon-link,.markdown-body h4 .mini-icon-link,.markdown-body h5 .mini-icon-link,.markdown-body h6 .mini-icon-link{color:#000;display:none}.markdown-body h1:hover a.anchor,.markdown-body h2:hover a.anchor,.markdown-body h3:hover a.anchor,.markdown-body h4:hover a.anchor,.markdown-body h5:hover a.anchor,.markdown-body h6:hover a.anchor{line-height:1;margin-left:-22px;padding-left:0;text-decoration:none;top:15%}.markdown-body h1:hover a.anchor .mini-icon-link,.markdown-body h2:hover a.anchor .mini-icon-link,.markdown-body h3:hover a.anchor .mini-icon-link,.markdown-body h4:hover a.anchor .mini-icon-link,.markdown-body h5:hover a.anchor .mini-icon-link,.markdown-body h6:hover a.anchor .mini-icon-link{display:inline-block}.markdown-body hr:after,.markdown-body hr:before{display:table;content:""}.markdown-body h1 code,.markdown-body h1 tt,.markdown-body h2 code,.markdown-body h2 tt,.markdown-body h3 code,.markdown-body h3 tt,.markdown-body h4 code,.markdown-body h4 tt,.markdown-body h5 code,.markdown-body h5 tt,.markdown-body h6 code,.markdown-body h6 tt{font-size:inherit}.markdown-body h1{color:#000;font-size:28px}.markdown-body h2{border-bottom:1px solid #CCC;color:#000;font-size:24px}.markdown-body h3{font-size:18px}.markdown-body h4{font-size:16px}.markdown-body h5{font-size:14px}.markdown-body h6{color:#777;font-size:14px}.markdown-body blockquote,.markdown-body dl,.markdown-body ol,.markdown-body p,.markdown-body pre,.markdown-body table,.markdown-body ul{margin:15px 0}.markdown-body hr{overflow:hidden;background:#e7e7e7;height:4px;padding:0;margin:16px 0;border:0;-moz-box-sizing:content-box;box-sizing:content-box}.markdown-body h1+p,.markdown-body h2+p,.markdown-body h3+p,.markdown-body h4+p,.markdown-body h5+p,.markdown-body h6+p,.markdown-body ol li>:first-child,.markdown-body ul li>:first-child{margin-top:0}.markdown-body hr:after{clear:both}.markdown-body a:first-child h1,.markdown-body a:first-child h2,.markdown-body a:first-child h3,.markdown-body a:first-child h4,.markdown-body a:first-child h5,.markdown-body a:first-child h6,.markdown-body>h1:first-child,.markdown-body>h1:first-child+h2,.markdown-body>h2:first-child,.markdown-body>h3:first-child,.markdown-body>h4:first-child,.markdown-body>h5:first-child,.markdown-body>h6:first-child{margin-top:0;padding-top:0}.markdown-body li p.first{display:inline-block}.markdown-body ol,.markdown-body ul{padding-left:30px}.markdown-body ol.no-list,.markdown-body ul.no-list{list-style-type:none;padding:0}.markdown-body ol ol,.markdown-body ol ul,.markdown-body ul ol,.markdown-body ul ul{margin-bottom:0}.markdown-body dl{padding:0}.markdown-body dl dt{font-size:14px;font-style:italic;font-weight:700;margin:15px 0 5px;padding:0}.markdown-body dl dt:first-child{padding:0}.markdown-body dl dt>:first-child{margin-top:0}.markdown-body dl dt>:last-child{margin-bottom:0}.markdown-body dl dd{margin:0 0 15px;padding:0 15px}.markdown-body blockquote>:first-child,.markdown-body dl dd>:first-child{margin-top:0}.markdown-body blockquote>:last-child,.markdown-body dl dd>:last-child{margin-bottom:0}.markdown-body blockquote{border-left:4px solid #DDD;color:#777;padding:0 15px}.markdown-body table th{font-weight:700}.markdown-body table td,.markdown-body table th{border:1px solid #CCC;padding:6px 13px}.markdown-body table tr{background-color:#FFF;border-top:1px solid #CCC}.markdown-body table tr:nth-child(2n){background-color:#F8F8F8}.markdown-body img{max-width:100%}.markdown-body span.frame{display:block;overflow:hidden}.markdown-body span.frame>span{border:1px solid #DDD;display:block;float:left;margin:13px 0 0;overflow:hidden;padding:7px;width:auto}.markdown-body span.frame span img{display:block;float:left}.markdown-body span.frame span span{clear:both;color:#333;display:block;padding:5px 0 0}.markdown-body span.align-center{clear:both;display:block;overflow:hidden}.markdown-body span.align-center>span{display:block;margin:13px auto 0;overflow:hidden;text-align:center}.markdown-body span.align-center span img{margin:0 auto;text-align:center}.markdown-body span.align-right{clear:both;display:block;overflow:hidden}.markdown-body span.align-right>span{display:block;margin:13px 0 0;overflow:hidden;text-align:right}.markdown-body span.align-right span img{margin:0;text-align:right}.markdown-body span.float-left{display:block;float:left;margin-right:13px;overflow:hidden}.markdown-body span.float-left span{margin:13px 0 0}.markdown-body span.float-right{display:block;float:right;margin-left:13px;overflow:hidden}.markdown-body span.float-right>span{display:block;margin:13px auto 0;overflow:hidden;text-align:right}.markdown-body code,.markdown-body tt{background-color:#F8F8F8;border:1px solid #EAEAEA;border-radius:3px;margin:0 2px;padding:0 5px;white-space:nowrap}.markdown-body pre>code{background:none;border:none;margin:0;padding:0;white-space:pre}.markdown-body .highlight pre,.markdown-body pre{background-color:#F8F8F8;border:1px solid #CCC;border-radius:3px;font-size:13px;line-height:19px;overflow:auto;padding:6px 10px}.markdown-body pre code,.markdown-body pre tt{background-color:transparent;border:none}</style>' + simplemdeEdit.markdown(preParse(contentOld))).wrap('<div/>').parent().html();
                            var html = $('<div class="markdown-body"/>').html('<style>.markdown-body{font-size:14px;line-height:1.6}.markdown-body>:first-child{margin-top:0!important}.markdown-body>:last-child{margin-bottom:0!important}.markdown-body a.absent{color:#C00}.markdown-body a.anchor{bottom:0;cursor:pointer;display:block;left:0;margin-left:-30px;padding-left:30px;position:absolute;top:0}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6{cursor:text;font-weight:700;margin:20px 0 10px;padding:0;position:relative}.markdown-body h1 .mini-icon-link,.markdown-body h2 .mini-icon-link,.markdown-body h3 .mini-icon-link,.markdown-body h4 .mini-icon-link,.markdown-body h5 .mini-icon-link,.markdown-body h6 .mini-icon-link{color:#000;display:none}.markdown-body h1:hover a.anchor,.markdown-body h2:hover a.anchor,.markdown-body h3:hover a.anchor,.markdown-body h4:hover a.anchor,.markdown-body h5:hover a.anchor,.markdown-body h6:hover a.anchor{line-height:1;margin-left:-22px;padding-left:0;text-decoration:none;top:15%}.markdown-body h1:hover a.anchor .mini-icon-link,.markdown-body h2:hover a.anchor .mini-icon-link,.markdown-body h3:hover a.anchor .mini-icon-link,.markdown-body h4:hover a.anchor .mini-icon-link,.markdown-body h5:hover a.anchor .mini-icon-link,.markdown-body h6:hover a.anchor .mini-icon-link{display:inline-block}.markdown-body hr:after,.markdown-body hr:before{display:table;content:""}.markdown-body h1 code,.markdown-body h1 tt,.markdown-body h2 code,.markdown-body h2 tt,.markdown-body h3 code,.markdown-body h3 tt,.markdown-body h4 code,.markdown-body h4 tt,.markdown-body h5 code,.markdown-body h5 tt,.markdown-body h6 code,.markdown-body h6 tt{font-size:inherit}.markdown-body h1{color:#000;font-size:28px}.markdown-body h2{border-bottom:1px solid #CCC;color:#000;font-size:24px}.markdown-body h3{font-size:18px}.markdown-body h4{font-size:16px}.markdown-body h5{font-size:14px}.markdown-body h6{color:#777;font-size:14px}.markdown-body blockquote,.markdown-body dl,.markdown-body ol,.markdown-body p,.markdown-body pre,.markdown-body table,.markdown-body ul{margin:15px 0}.markdown-body hr{overflow:hidden;background:#e7e7e7;height:4px;padding:0;margin:16px 0;border:0;-moz-box-sizing:content-box;box-sizing:content-box}.markdown-body h1+p,.markdown-body h2+p,.markdown-body h3+p,.markdown-body h4+p,.markdown-body h5+p,.markdown-body h6+p,.markdown-body ol li>:first-child,.markdown-body ul li>:first-child{margin-top:0}.markdown-body hr:after{clear:both}.markdown-body a:first-child h1,.markdown-body a:first-child h2,.markdown-body a:first-child h3,.markdown-body a:first-child h4,.markdown-body a:first-child h5,.markdown-body a:first-child h6,.markdown-body>h1:first-child,.markdown-body>h1:first-child+h2,.markdown-body>h2:first-child,.markdown-body>h3:first-child,.markdown-body>h4:first-child,.markdown-body>h5:first-child,.markdown-body>h6:first-child{margin-top:0;padding-top:0}.markdown-body li p.first{display:inline-block}.markdown-body ol,.markdown-body ul{padding-left:30px}.markdown-body ol.no-list,.markdown-body ul.no-list{list-style-type:none;padding:0}.markdown-body ol ol,.markdown-body ol ul,.markdown-body ul ol,.markdown-body ul ul{margin-bottom:0}.markdown-body dl{padding:0}.markdown-body dl dt{font-size:14px;font-style:italic;font-weight:700;margin:15px 0 5px;padding:0}.markdown-body dl dt:first-child{padding:0}.markdown-body dl dt>:first-child{margin-top:0}.markdown-body dl dt>:last-child{margin-bottom:0}.markdown-body dl dd{margin:0 0 15px;padding:0 15px}.markdown-body blockquote>:first-child,.markdown-body dl dd>:first-child{margin-top:0}.markdown-body blockquote>:last-child,.markdown-body dl dd>:last-child{margin-bottom:0}.markdown-body blockquote{border-left:4px solid #DDD;color:#777;padding:0 15px}.markdown-body table th{font-weight:700}.markdown-body table td,.markdown-body table th{border:1px solid #CCC;padding:6px 13px}.markdown-body table tr{background-color:#FFF;border-top:1px solid #CCC}.markdown-body table tr:nth-child(2n){background-color:#F8F8F8}.markdown-body img{max-width:100%}.markdown-body span.frame{display:block;overflow:hidden}.markdown-body span.frame>span{border:1px solid #DDD;display:block;float:left;margin:13px 0 0;overflow:hidden;padding:7px;width:auto}.markdown-body span.frame span img{display:block;float:left}.markdown-body span.frame span span{clear:both;color:#333;display:block;padding:5px 0 0}.markdown-body span.align-center{clear:both;display:block;overflow:hidden}.markdown-body span.align-center>span{display:block;margin:13px auto 0;overflow:hidden;text-align:center}.markdown-body span.align-center span img{margin:0 auto;text-align:center}.markdown-body span.align-right{clear:both;display:block;overflow:hidden}.markdown-body span.align-right>span{display:block;margin:13px 0 0;overflow:hidden;text-align:right}.markdown-body span.align-right span img{margin:0;text-align:right}.markdown-body span.float-left{display:block;float:left;margin-right:13px;overflow:hidden}.markdown-body span.float-left span{margin:13px 0 0}.markdown-body span.float-right{display:block;float:right;margin-left:13px;overflow:hidden}.markdown-body span.float-right>span{display:block;margin:13px auto 0;overflow:hidden;text-align:right}.markdown-body code,.markdown-body tt{background-color:#F8F8F8;border:1px solid #EAEAEA;border-radius:3px;margin:0 2px;padding:0 5px;white-space:nowrap}.markdown-body pre>code{background:none;border:none;margin:0;padding:0;white-space:pre}.markdown-body .highlight pre,.markdown-body pre{background-color:#F8F8F8;border:1px solid #CCC;border-radius:3px;font-size:13px;line-height:19px;overflow:auto;padding:6px 10px}.markdown-body pre code,.markdown-body pre tt{background-color:transparent;border:none}</style>' + simplemdeEdit.markdown(preParse(content))).wrap('<div/>').parent().html();

                            $.post('/admin/chat/update', {
                                id: $btn.closest('.comment').attr('data-id'),
                                baseURL: baseURL,
                                usernames: parseUsernames(content).join(','),
                                groups: parseGroupNames(content).join(','),
                                content: content,
                                diff: Utils.diffS(contentOld, content),
                                // contentHtmlOld: htmlOld,
                                // contentHtml: html,
                                version: data.data.version
                            }, function(data, textStatus, xhr) {
                                if (data.success) {
                                    $btn.closest('.comment').find('.content .text.markdown-body').html(simplemdeEdit.markdown(preParse(data.data.content)));
                                    $btn.closest('.comment').attr('data-version', data.data.version);
                                    simplemdeEdit.value('');
                                    simplemdeEdit.clearAutosavedValue();
                                    toastr.success('更新成功!');
                                    $('.ad-chat-edit').modal('hide');
                                } else {
                                    toastr.error(data.data, '更新失败!');
                                }
                            });

                            return false;
                        }
                    }).modal('show');
                } else {
                    toastr.error(data.data, '获取失败!');
                }
            });
        });

        $('body').on('dblclick', '.comments .comment .text.markdown-body', function(event) {
            $edit = $(this).closest('.comment').find('.actions .edit');
            if (event.altKey && $edit.size() !== 0) {
                $edit.click();
            } else if (event.ctrlKey) {
                commentRead($(this).closest('.comment'));
            }
        });

        $('body').on('click', '.comments .comment .content .author, .comments .comment .avatar, .ui.comments .comment .text span.at-user, .pp-translate .ui.items>.item>.content>.description span.at-user, .fd-dynamic .event .content .summary .user, .pp-translate .group-user, .pp-translate .user-group', function(event) {
            event.preventDefault();
            insertAtUserOrGroup(cm, $(this).attr('data-value'));
            s2b();
            cm.focus();
        });

        $('body').on('click', '.ui.comments .comment .text span.at-group', function(event) {
            event.preventDefault();
            insertAtUserOrGroup(cm, $(this).attr('data-value'), true);
            s2b();
            cm.focus();
        });

        $('body').on('click', '.btn-chat-more', function(event) {
            event.preventDefault();

            $btn = $(this);

            $.get('/admin/chat/more/old', {
                startId: $btn.next(".comment").attr('data-id'),
                size: $('input:hidden[name="page.size"]').val()
            }, function(data) {
                if (data.success) {

                    if (data.data.content.length == 0) {
                        toastr.warning('没有更多数据了!');
                        return;
                    }

                    var $more = convertChat(data.data.content, null, false);

                    $more.insertAfter($('.btn-chat-more'));
                    $('.btn-chat-more').text('加载更多(' + data.data.countMore + ')');

                    s2mk();

                    jQuery(".timeago").timeago();
                    !data.data.hasMore && $btn.remove();
                    toastr.success('加载成功!');
                } else {
                    toastr.error(data.data, '加载失败!');
                }
            });
        });

        $('body').on('click', '.btn-chat-pre-more', function(event) {
            event.preventDefault();

            $btn = $(this);

            $.get('/admin/chat/more/new', {
                startId: $btn.prev(".comment").attr('data-id'),
                size: $('input:hidden[name="page.size"]').val()
            }, function(data) {
                if (data.success) {

                    if (data.data.content.length == 0) {
                        toastr.warning('没有更多数据了!');
                        return;
                    }

                    var $more = convertChat(data.data.content, null, true);
                    $more.insertBefore($('.btn-chat-pre-more'));
                    $('.btn-chat-pre-more').text('加载更多(' + data.data.countMore + ')');

                    s2mk();

                    jQuery(".timeago").timeago();

                    !data.data.hasMore && $btn.remove();
                    toastr.success('加载成功!');
                } else {
                    toastr.error(data.data, '加载失败!');
                }
            });
        });

        var actionMapping = {
            'Create': '添加',
            'Update': '更新',
            "Delete": '删除'
        };
        var propMapping = {
            'TranslateItem': '内容',
            'Key': '名称',
            'Watchers': '关注者',
            'Labels': '标签'
        };

        $('.btn-log-more').click(function(event) {
            $btn = $(this);

            $.get('/admin/chat/moreLogs', {
                page: $('input:hidden[name="page.number.next.logs"]').val(),
                size: $('input:hidden[name="page.size.logs"]').val()
            }, function(data) {
                if (data.success) {

                    if (data.data.content.length == 0) {
                        toastr.warning('没有更多数据了!');
                        return;
                    }

                    $('input:hidden[name="page.number.next.logs"]').val(data.data.number + 1);
                    $('input:hidden[name="page.size.logs"]').val(data.data.size);

                    $.each(data.data.content, function(index, log) {
                        if (log.creator.name) {
                            log.creator.iconName = log.creator.name.substr(log.creator.name.length - 1).toUpperCase();
                        }

                        if (log.properties == 'Labels') log.isLabels = true;
                        if (log.properties == 'Watchers') log.isWatchers = true;
                        if (log.oldValue != null) log.isOldValue = true;

                        log.actionMapping = actionMapping[log.action];
                        log.propertiesMapping = propMapping[log.properties];
                        var d = new Date(log.createDate);
                        log.createDate = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                    });
                    $("#logMoreTpl").tmpl(data.data.content).appendTo('.fd-dynamic');

                    $('.btn-log-more').text('加载更多(' + (data.data.totalElements - (data.data.number + 1) * data.data.size) + ')');

                    jQuery(".timeago").timeago();
                    Utils.showMappedTxt('.mapping-user');

                    data.data.last && $btn.remove();
                    toastr.success('加载成功!');
                } else {
                    toastr.error(data.data, '加载失败!');
                }
            });
        });

        /**
         * 获取沟通新消息
         * @param  {[type]}  lastId [description]
         * @param  {Boolean} isAuto [description]
         * @return {[type]}         [description]
         */
        function getChatNews(isAuto) {

            var url = isAuto ? '/admin/chat/getNews/unmask' : '/admin/chat/getNews';
            var $btn = $('.btn-get-chat-news');

            if (!$btn.attr('data-value')) {
                return;
            }

            isFetchNews = true;

            $.get(url, {
                lastId: $btn.attr('data-value')
            }, function(data) {
                if (data.success) {

                    $btn.hide();

                    if ($.isArray(data.data)) { // 不刷新追加
                        if (data.data.length == 0) {
                            return;
                        }

                        var preMore = $('.btn-chat-pre-more').size() == 1;
                        var $domBefore = preMore ? $('.btn-chat-pre-more') : $('.fm-reply');

                        var $more = convertChat(data.data);
                        $more.insertBefore($domBefore);
                        jQuery(".timeago").timeago();
                        s2b();
                    }
                    toastr.success('刚刚刷新获取到' + data.data.length + '条新消息!');
                } else {
                    toastr.error(data.data, '获取失败!');
                }
            }).always(function() {
                isFetchNews = false;
            });
        }

        $('.btn-get-chat-news').click(function(event) {
            event.preventDefault();

            getChatNews(false);
        });

        function deskNotify(msg) {

            if (notify.isSupported) {
                var level = notify.permissionLevel();
                if (level == notify.PERMISSION_GRANTED) {
                    notify.createNotification("TMS沟通动态消息通知", {
                        body: msg,
                        icon: {
                            x16: '/image/tms-x16.ico',
                            x32: '/image/tms-x32.png'
                        },
                        tag: 'tms-admin-dynamic-chat-new-msg',
                    });
                } else if (level == notify.PERMISSION_DEFAULT) {
                    notify.requestPermission(function() {
                        deskNotify(msg);
                    });
                } else {
                    console.log('用户拒绝桌面通知!')
                }
            } else {
                console.log('浏览器不支持桌面通知!')
            }
        }

        // $('.btn-get-chat-news').show();
        // 轮询最新沟通消息
        window.poll.start(function(resetCb, stopCb) {

            var $last = $('.chat .comments .comment').last();
            var $first = $('.fd-dynamic .event').first();

            $.get('/admin/chat/poll/unmask', {
                lastEvtId: $first.size() == 0 ? -1 : $first.attr('data-id'),
                lastId: $last.size() == 0 ? -1 : $last.attr('data-id'),
                isAt: $onlyAt.checkbox('is checked')
            }, function(data) {
                if (data.success) {

                    // 如果有最新消息没有有分页 & 轮询发现有新消息
                    if (($('.btn-chat-pre-more').size() == 0) && data.data[1] > 0) {
                        resetCb();
                        var lastCnt = $('.btn-get-chat-news').children('.lbl-chat-news-count').text();
                        $('.btn-get-chat-news').children('.lbl-chat-news-count').text(data.data[1]);
                        $('.btn-get-chat-news').attr('data-value', data.data[0]).show();
                        // 如果自动刷新消息开启,则立即获取消息
                        $autoCR.checkbox('is checked') && getChatNews(true);

                        if (lastCnt != data.data[1]) {
                            deskNotify('您有' + data.data[1] + '条沟通新消息!');
                        }

                    } else {
                        $('.btn-get-chat-news').attr('data-value', data.data[0]).hide();
                    }

                    if (data.data[4] > 0) { // 有@消息
                        var atCnt = data.data[4];
                        $('.btn-get-chat-ats').children('.lbl-chat-ats-count').text(atCnt > 99 ? '99+' : atCnt);
                        $('.btn-get-chat-ats').show();
                    } else {
                        $('.btn-get-chat-ats').hide();
                    }

                    if (data.msgs.length > 0) {

                        if (data.msgs[0].length > 0) {
                            resetCb();
                            $.each(data.msgs[0], function(index, log) {
                                if (log.creator.name) {
                                    log.creator.iconName = log.creator.name.substr(log.creator.name.length - 1).toUpperCase();
                                }
                                if (log.properties == 'Labels') log.isLabels = true;
                                if (log.properties == 'Watchers') log.isWatchers = true;
                                if (log.oldValue != null) log.isOldValue = true;

                                log.actionMapping = actionMapping[log.action];
                                log.propertiesMapping = propMapping[log.properties];
                                var d = new Date(log.createDate);
                                log.createDate = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                            });
                            $("#logMoreTpl").tmpl(data.msgs[0]).prependTo('.fd-dynamic');
                            jQuery(".timeago").timeago();
                            Utils.showMappedTxt('.mapping-user');

                            var $toast = toastr.info('刚刚有' + data.msgs.length + '条动态更新');
                            $toast && $toast.click(function(event) {
                                event.preventDefault();
                                $('.main.container .right.rail .sticky').scrollTo(0, 300);
                                $toast.remove();
                            });

                            deskNotify('您刚刚有' + data.msgs.length + '条动态更新!');
                        }

                    }

                }
            }).fail(function() {
                stopCb();
                Utils.errorAutoTry(function() {
                    resetCb();
                }, 15);
            });
        });

        // clipboard paste image
        $('.fm-reply .CodeMirror textarea').pastableTextarea().on('pasteImage', function(ev, data) {

            $.post('/admin/file/base64', {
                dataURL: data.dataURL,
                type: data.blob.type
            }, function(data, textStatus, xhr) {
                if (data.success) {
                    insertComment(cm, '![{name}]({baseURL}{path}{uuidName})'
                        .replace(/\{name\}/g, data.data.name)
                        .replace(/\{baseURL\}/g, baseURL)
                        // .replace(/\{path\}/g, 'admin/file/download/')
                        // .replace(/\{uuidName\}/g, data.data.id));
                        .replace(/\{path\}/g, data.data.path)
                        .replace(/\{uuidName\}/g, data.data.uuidName));
                }
            });
        }).on('pasteImageError', function(ev, data) {
            toastr.error(data.message, '剪贴板粘贴图片错误!');
        });

        // clipboard paste image
        $('.fm-edit-reply .CodeMirror textarea').pastableTextarea().on('pasteImage', function(ev, data) {

            $.post('/admin/file/base64', {
                dataURL: data.dataURL,
                type: data.blob.type
            }, function(data, textStatus, xhr) {
                if (data.success) {
                    insertComment(cme, '![{name}]({baseURL}{path}{uuidName})'
                        .replace(/\{name\}/g, data.data.name)
                        .replace(/\{baseURL\}/g, baseURL)
                        // .replace(/\{path\}/g, 'admin/file/download/')
                        // .replace(/\{uuidName\}/g, data.data.id));
                        .replace(/\{path\}/g, data.data.path)
                        .replace(/\{uuidName\}/g, data.data.uuidName));
                }
            });
        }).on('pasteImageError', function(ev, data) {
            toastr.error(data.message, '剪贴板粘贴图片错误!');
        });


        // 翻译popup
        $('body').on('mouseenter', '#context a[href*="admin/translate"]:not(.pp-not)', function(event) {
            event.preventDefault();
            var $a = $(this);

            if ($a.closest('.pp-translate').size() != 0) {
                return;
            }

            if (!url('?id', $a.attr('href'))) {
                return;
            }

            $('.pp-translate').empty();

            $(this).popup({
                popup: $('.pp-translate'),
                hoverable: true,
                inline: false,
                movePopup: false,
                position: 'top left',
                maxSearchDepth: 50,
                delay: {
                    show: 300,
                    hide: 300
                },
                onShow: function() {
                    var $pp = $(this).html('加载中...');
                    $.get('admin/translate/getById/unmask', {
                        id: url('?id', $a.attr('href'))
                    }, function(data) {
                        if (data.success) {
                            var translate = data.data;
                            var d = new Date(translate.createDate);
                            translate.createDateFormat = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                            $("#tansPpTpl").tmpl(data.data).appendTo($pp.empty());

                            Utils.showMappedTxt('.pp-translate .mapping-user');
                            $('.pp-translate .timeago').timeago();
                        } else {
                            toastr.error(data.data, "加载失败!");
                        }
                    });
                }
            }).popup('show');
        });

        // 消息popup
        $('body').on('mouseenter', '#context a[href*="admin/dynamic"]:not(.pp-not)', function(event) {
            event.preventDefault();
            var $a = $(this);

            if ($a.closest('.pp-translate').size() != 0) {
                return;
            }

            $('.pp-translate').empty();

            $(this).popup({
                popup: $('.pp-translate'),
                hoverable: true,
                inline: false,
                movePopup: false,
                position: 'top left',
                maxSearchDepth: 50,
                delay: {
                    show: 300,
                    hide: 300
                },
                onShow: function() {
                    var $pp = $(this).html('加载中...');
                    $.get('admin/chat/get/unmask', {
                        id: url('?id', $a.attr('href'))
                    }, function(data) {
                        if (data.success) {
                            var chat = data.data;
                            chat.creatorName = chat.creator.name ? chat.creator.name : chat.creator.username;
                            var d = new Date(chat.createDate);
                            chat.createDateFormat = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                            chat.contentMd = simplemde.markdown(preParse(chat.content));

                            $("#chatMsgPpTpl").tmpl(data.data).appendTo($pp.empty());
                            $('.pp-translate .timeago').timeago();
                        } else {
                            toastr.error(data.data, "加载失败!");
                        }
                    });
                }
            }).popup('show');
        });

        // 用户信息popup
        $('#context').on('mouseenter', 'span[data-value].at-user:not(.pp-not)', function(event) {
            showUserInfoPp($(this), event);
        });
        // 用户信息popup
        $('#context').on('mouseenter', 'a[data-value].avatar:not(.pp-not)', function(event) {
            showUserInfoPp($(this), event);
        });
        // 用户信息popup
        $('#context').on('mouseenter', 'a[data-value].author:not(.pp-not)', function(event) {
            showUserInfoPp($(this), event);
        });

        function showUserInfoPp($a, event) {

            event.preventDefault();

            if ($a.closest('.pp-translate').size() != 0) {
                return;
            }

            $('.pp-translate').empty();

            $a.popup({
                popup: $('.pp-translate'),
                hoverable: true,
                inline: false,
                movePopup: false,
                position: 'top left',
                maxSearchDepth: 50,
                delay: {
                    show: 300,
                    hide: 300
                },
                onShow: function() {
                    var $pp = $(this).html('加载中...');

                    if ($a.attr('data-value') == 'all') {
                        $.get('admin/user/all', {
                            enabled: true
                        }, function(data) {
                            if (data.success) {
                                var users = data.data;
                                var model = {
                                    count: users.length,
                                    users: users
                                };
                                $("#allUserInfoPpTpl").tmpl(model).appendTo($pp.empty());
                                Utils.showMappedTxt('.pp-translate .mapping-user');
                            } else {
                                toastr.error(data.data, "加载失败!");
                            }
                        });
                    } else {

                        $.get('admin/user/get', {
                            username: $a.attr('data-value')
                        }, function(data) {
                            if (data.success) {
                                var user = data.data;
                                var userGroups = data.msgs[0];
                                if (userGroups && userGroups.length > 0) {
                                    user.userGroups = data.msgs[0];
                                }

                                var d = new Date(user.createDate);
                                user.createDateFormat = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                                user.sts = user.enabled ? '启用中' : '已禁用';
                                if (user.lastLoginDate) {
                                    d = new Date(user.lastLoginDate);
                                    user.lastLoginDateFormat = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                                }

                                $("#userInfoPpTpl").tmpl(user).appendTo($pp.empty());
                                Utils.showMappedTxt('.pp-translate .mapping-user');
                                $('.pp-translate .timeago').timeago();
                            } else {
                                toastr.error(data.data, "加载失败!");
                            }
                        });

                    }
                }
            }).popup('show');
        }

        // 用户组信息popup
        $('#context').on('mouseenter', 'span[data-value].at-group:not(.pp-not)', function(event) {
            showUserGroupInfoPp($(this), event);
        });

        function showUserGroupInfoPp($a, event) {

            event.preventDefault();

            if ($a.closest('.pp-translate').size() != 0) {
                return;
            }

            $('.pp-translate').empty();

            $a.popup({
                popup: $('.pp-translate'),
                hoverable: true,
                inline: false,
                movePopup: false,
                position: 'top left',
                maxSearchDepth: 50,
                delay: {
                    show: 300,
                    hide: 300
                },
                onShow: function() {
                    var $pp = $(this).html('加载中...');
                    $.get('admin/user/getGroup', {
                        groupName: $a.attr('data-value')
                    }, function(data) {
                        if (data.success) {
                            var group = data.data;
                            var d = new Date(group.createDate);
                            group.createDateFormat = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();

                            var gms = [];
                            $.each(group.groupMembers, function(index, gm) {
                                var userInfo = allUserInfo[gm.username];
                                if (userInfo && userInfo.status == 'true') {
                                    gms.push(gm);
                                }
                            });
                            group.groupMembers = gms;
                            group.count = group.groupMembers.length;

                            $("#userGroupInfoPpTpl").tmpl(data.data).appendTo($pp.empty());
                            Utils.showMappedTxt('.pp-translate .mapping-user');
                            $('.pp-translate .timeago').timeago();
                        } else {
                            toastr.error(data.data, "加载失败!");
                        }
                    });
                }
            }).popup('show');
        }

        function commentRead($comment) {
            var $md = $comment.find('.content .markdown-body');
            $('.ad-comment-page-dimmer')
                .show()
                .find('.container').css({
                    'height': $(window).height(),
                    'align-items': $md.height() < $(window).height() ? 'center' : 'inherit'
                })
                .find('.text')
                .empty()
                .append($md.clone());

            $('.ad-comment-page-dimmer').addClass('dimmer').dimmer({
                onShow: function() {
                    $('body').addClass('blurring');
                },
                onHide: function() {
                    $('body').removeClass('blurring');
                    $('.ad-comment-page-dimmer').removeClass('dimmer').hide();
                }
            }).dimmer('show');
        }

        // $('body').on('dblclick', '.chat .comments .comment', function(event) {
        //     event.preventDefault();
        //     commentRead($(this));
        // });
        $('body').on('click', '.ad-comment-page-dimmer .container', function(event) {
            if (event.target == event.currentTarget) {
                $(this).closest('.page.dimmer').dimmer('hide');
            }
        });

        //-----------------------------------------------------------chat comment more-actions start
        $('body').on('click', '.comments .comment .dd-more-actions .btn-read', function(event) {
            event.preventDefault();
            commentRead($(this).closest('.comment'));
        });
        $('body').on('click', '.chat .comments .comment .dd-more-actions .btn-wiki', function(event) {
            event.preventDefault();
            $btn = $(this);
            $('.ad-msg-as-wiki').modal({
                onShow: function() {
                    var $md = $(this);
                    $md.find('.ui.form').form('clear');

                    var content = $btn.closest('.comment').find('.content .text.markdown-body').attr('data-content');
                    var lines = content.split('\n');
                    $.each(lines, function(index, line) {
                        line = $.trim(line);
                        var arr = line.split(/\s+/);
                        if (arr.length > 1) {
                            if (/^#+$/.test(arr[0])) {
                                $md.find('input[name="title"]').val(line.replace(/^#+\s+/, ''));
                                return false;
                            }
                        }
                    });
                },
                onApprove: function() {
                    $md = $(this);
                    $.post('/admin/chat/asWiki', {
                        id: $btn.closest('.comment').attr('data-id'),
                        baseURL: baseURL,
                        title: $md.find('input[name="title"]').val(),
                        privated: $md.find('.ui.checkbox').checkbox('is checked'),
                        labels: $md.find('.dd-labels').dropdown('get value')
                    }, function(data, textStatus, xhr) {
                        if (data.success) {
                            $btn.remove();
                            toastr.success('消息转博文成功!');
                        } else {
                            toastr.error(data.data, '消息转博文失败!');
                        }
                    });
                }
            }).modal('show');
        });
        $('body').on('click', '.comments .comment .dd-more-actions .btn-openEdit', function(event) {
            event.preventDefault();
            var $btn = $(this);

            var sts = $btn.attr('data-value') == 'true';

            $.post('admin/chat/openEdit', {
                id: $btn.closest('.comment').attr('data-id'),
                open: !sts
            }, function(data, textStatus, xhr) {
                if (data.success) {
                    toastr.success(sts ? '关闭协作操作成功!' : '开启协作操作成功!');
                    $btn.text(sts ? '开启协作' : '关闭协作');
                    $btn.attr('data-value', !sts)
                } else {
                    toastr.error(data.data, "操作失败!");
                }
            });

        });
        //-----------------------------------------------------------chat comment more-actions end

        $('body').on('click', '.cbutton', function(event) {
            event.preventDefault();
            $btn = $(this);
            $btn.addClass('cbutton--click');
            setTimeout(function() {
                $btn.removeClass('cbutton--click');
            }, 500);
        });

        // emoji
        var emoji = (function() {

            // 表情
            var emojis = [
                ':smile:',
                ':laughing:',
                ':blush:',
                ':smiley:',
                ':relaxed:',
                ':smirk:',
                ':heart_eyes:',
                ':kissing_heart:',
                ':kissing_closed_eyes:',
                ':flushed:',
                ':relieved:',
                ':satisfied:',
                ':grin:',
                ':wink:',
                ':stuck_out_tongue_winking_eye:',
                ':stuck_out_tongue_closed_eyes:',
                ':unamused:',
                ':sweat_smile:',
                ':sweat:',
                ':disappointed_relieved:',
                ':weary:',
                ':pensive:',
                ':disappointed:',
                ':confounded:',
                ':fearful:',
                ':cold_sweat:',
                ':persevere:',
                ':cry:',
                ':sob:',
                ':joy:',
                ':astonished:',
                ':scream:',
                ':tired_face:',
                ':angry:',
                ':rage:',
                ':triumph:',
                ':sleepy:',
                ':yum:',
                ':mask:',
                ':sunglasses:',
                ':dizzy_face:',
                ':imp:',
                ':smiling_imp:',
                ':neutral_face:',
                ':no_mouth:',
                ':innocent:',
                ':alien:',
                ':yellow_heart:',
                ':blue_heart:',
                ':heart:',
                ':broken_heart:',
                ':heartbeat:',
                ':heartpulse:',
                ':two_hearts:',
                ':revolving_hearts:',
                ':cupid:',
                ':sparkling_heart:',
                ':sparkles:',
                ':star:',
                ':dizzy:',
                ':boom:',
                ':anger:',
                ':exclamation:',
                ':question:',
                ':grey_exclamation:',
                ':grey_question:',
                ':zzz:',
                ':dash:',
                ':sweat_drops:',
                ':notes:',
                ':musical_note:',
                ':fire:',
                ':hankey:',
                ':thumbsup:',
                ':thumbsdown:',
                ':ok_hand:',
                ':punch:',
                ':fist:',
                ':v:',
                ':wave:',
                ':raised_hand:',
                ':open_hands:',
                ':point_up:',
                ':point_down:',
                ':point_left:',
                ':point_right:',
                ':raised_hands:',
                ':pray:',
                ':point_up_2:',
                ':clap:',
                ':muscle:',
                ':feet:',
                ':lips:',
                ':kiss:',
                ':droplet:',
                ':ear:',
                ':eyes:',
                ':nose:',
                ':tongue:',
                ':love_letter:',
            ];

            return {
                init: function($pp, cm) {

                    if ($pp.children().size() != 0) {
                        return;
                    }

                    isInited = true;

                    var $wrap = $('<div></div>');
                    $.each(emojis, function(index, e) {
                        var $img = $(emojione.shortnameToImage(e)).attr('data-name', e).attr('title', e).click(function(event) {
                            var cursor = cm.getCursor();
                            if (cursor) {
                                cm.replaceRange('![{name}]({protocol}:{src})'
                                    .replace(/\{name\}/g, $(this).attr('data-name'))
                                    .replace(/\{protocol\}/g, url('protocol'))
                                    .replace(/\{src\}/g, $(this).attr('src')), cursor, cursor);
                                cm.focus();
                            }
                        });
                        $wrap.append($img);
                    });

                    $pp.append($wrap);
                }
            };

        })();

        // -------------------------------------------------------------------------------- 滚动至消息头 start


        $('.btn-chat-s2h').click(function() {
            var $btn = $(this);
            s2mk($btn.data('target'));
        });

        $('.btn-chat-s2b').click(function() {
            var $t = $('.btn-chat-s2h').data('target');
            $('.btn-chat-s2h').data('target', $t.next());
            s2mk($('.btn-chat-s2h').data('target'));
        });

        $('body').on('mouseenter', '.chat .comment .text.markdown-body', function(event) {
            event.preventDefault();

            var $c = $(this).closest('.comment');

            $.get('admin/chat/getReplies', {
                id: $c.attr('data-id')
            }, function(data) {
                if (data.success) {

                    var chats = data.data;
                    if (chats.length > 0) {
                        $('.pp-comment-reply').find('.comments').empty();
                        $c.popup({
                            popup: $('.pp-comment-reply'),
                            hoverable: true,
                            inline: false,
                            movePopup: false,
                            position: 'bottom left',
                            prefer: 'opposite',
                            maxSearchDepth: 50,
                            // observeChanges: false,
                            // offset: -50,
                            // distanceAway: 50,
                            delay: {
                                show: 300,
                                hide: 300
                            },
                            onShow: function() {
                                $(this).find('.comments').html('加载中...');
                            },
                            onHidden: function() {
                                $c.popup({});
                            },
                            onVisible: function() {
                                var $pp = $(this); //.html('加载中...');

                                var isSuperRole = $('input:hidden[name="role.super"]').val();
                                var loginUsername = $('input:hidden[name="user.username"]').val();
                                $.each(chats, function(index, chat) {
                                    chat.contentMd = simplemde.markdown(preParse(chat.content));
                                    chat.marked = '';
                                    chat.marker = '';
                                    chat.zanCount = (chat.voteZan) ? chat.voteZan.split(',').length : 0;
                                    chat.caiCount = (chat.voteCai) ? chat.voteCai.split(',').length : 0;
                                    chat.textShare = baseURL + 'admin/dynamic?id=' + chat.id;
                                    if (chat.creator.name) {
                                        chat.creator.iconName = chat.creator.name.substr(chat.creator.name.length - 1).toUpperCase();
                                    }

                                    chat.isOpenEdit = !!chat.openEdit;
                                    chat.openEditText = chat.isOpenEdit ? '关闭协作' : '开启协作';

                                    if (isSuperRole == 'true' || loginUsername == chat.creator.username) {
                                        chat.actions = true;
                                    }
                                    if (isSuperRole == 'true' || loginUsername == chat.creator.username || chat.isOpenEdit) {
                                        chat.isEditable = true;
                                    }
                                    var d = new Date(chat.createDate);
                                    chat.createDateFormat = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                                });
                                var $more = $("#chatReplyTpl").tmpl(chats).appendTo($pp.find('.comments').empty().width($c.width() * 0.6));
                                $more.find('.ui.dropdown.dd-more-actions').dropdown({
                                    action: 'hide',
                                    direction: 'downward'
                                });
                                $more.find('.ui.dropdown.dd-quick-reply').dropdown({
                                    action: 'hide',
                                    direction: 'downward'
                                });

                                $pp.width($pp.width() + 1);
                                $pp.width($pp.width() - 1);

                                $('.pp-comment-reply .timeago').timeago();
                            }
                        }).popup('show');

                    }
                    // console.log(data.data);
                } else {
                    toastr.error(data.data, '获取回复消息失败!');
                }
            });
        });

        $('body').on('mouseenter', '.chat .comment', function(event) {
            event.preventDefault();

            var $c = $(this);

            var $header = $(event.target).closest('.comment').find('.content a.author');
            if ($header.size() > 0) {
                $('.btn-chat-s2h').data('target', $header.closest('.comment'));
                if (!Utils.isElementInViewport($header)) {
                    $('.btn-chat-s2h').show();
                    $('.btn-chat-s2b').show();
                }
            }

            $('.wiki-dir .wiki-dir-tree').empty().append(Utils.dir($(this)));
            if ($('.wiki-dir a.wiki-dir-item').size() == 0) {
                $('.btn-chat-dir').hide();
            } else {
                $('.btn-chat-dir').show();
            }
        });

        $('.chat').mouseleave(function(event) {
            $('.btn-chat-s2h').removeData('target').hide();
            $('.btn-chat-s2b').hide();
        });

        $(window).scroll(jQuery.debounce(200, function() {
            var $t = $('.btn-chat-s2h').data('target');
            var $header = $t && $t.find('.content a.author');
            if ($header && $header.size() > 0 && !Utils.isElementInViewport($header)) {
                $('.btn-chat-s2h').show();
                $('.btn-chat-s2b').show();
            } else {
                $('.btn-chat-s2h').hide();
                $('.btn-chat-s2b').hide();
            }
        }));

        // -------------------------------------------------------------------------------- 滚动至消息头 end

        // -------------------------------------------------------------------------------- wiki dir start

        $('body').on('click', '.wiki-dir-item', function(event) {
            event.preventDefault();
            s2mk($('#' + $(this).attr('data-id')));
        });
        $('.btn-chat-dir').hover(function() {
            $('.wiki-dir').show();
        }, function() {
            if (!$('.btn-wiki-dir-lock').hasClass('lock')) {
                $('.wiki-dir').hide();
            }
        });
        $('.btn-wiki-dir-lock').click(function(event) {
            $(this).toggleClass('lock unlock alternate');
        });
        // -------------------------------------------------------------------------------- wiki dir end

        // -------------------------------------------------------------------------------- chat ats start
        $('.btn-get-chat-ats').click(function(event) {

            window.poll.reset(); // 重置轮询频率

            $('.pp-ats-content').children('.ui.list').empty().append('<div class="item">加载中...</div>');

            $('.pp-ats').show();

            $.get('/admin/chat/getAtChats/unmask', {
                size: 20
            }, function(data) {
                if (data.success) {
                    var chatAts = data.data.content;
                    var chats = [];
                    $.each(chatAts, function(index, chatAt) {
                        chatAt.chat.chatAtId = chatAt.id;
                        chats.push(chatAt.chat);
                    });

                    $.each(chats, function(index, chat) {
                        chat.contentBrief = chat.content.length > 50 ? chat.content.substr(0, 47) + '...' : chat.content;
                        if (chat.creator.name) {
                            chat.iconName = chat.creator.name.substr(chat.creator.name.length - 1).toUpperCase();
                        }
                        var d = new Date(chat.createDate);
                        chat.createDateFormat = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                    });
                    $("#chatAtsTpl").tmpl(chats).appendTo($('.pp-ats-content').children('.ui.list').empty());
                    $('.pp-ats-content .timeago').timeago();
                }
            });
        });
        $('.btn-get-chat-ats').hover(function() {

        }, function() {
            if (!$('.pp-ats-lock').hasClass('lock') && !$('.pp-translate:visible').size()) {
                $('.pp-ats').hide();
            }
        });

        $('.pp-ats-lock').click(function(event) {
            event.preventDefault();
            event.stopImmediatePropagation();
            $(this).toggleClass('lock unlock alternate');
        });
        // -------------------------------------------------------------------------------- chat ats end

        // -------------------------------------------------------------------------------- chat stows end
        $('.btn-get-chat-stows').click(function(event) {

            $('.pp-stows-content').children('.ui.list').empty().append('<div class="item">加载中...</div>');

            $('.pp-stows').show();

            $.get('/admin/chat/getStows/unmask', function(data) {
                if (data.success) {
                    var chatStows = data.data;
                    var chats = [];
                    $.each(chatStows, function(index, chatStow) {
                        chatStow.chat.chatStowId = chatStow.id;
                        chats.push(chatStow.chat);
                    });

                    $.each(chats, function(index, chat) {
                        chat.contentBrief = chat.content.length > 50 ? chat.content.substr(0, 47) + '...' : chat.content;
                        if (chat.creator.name) {
                            chat.iconName = chat.creator.name.substr(chat.creator.name.length - 1).toUpperCase();
                        }
                        var d = new Date(chat.createDate);
                        chat.createDateFormat = d.getFullYear() + '/' + (d.getMonth() + 1) + '/' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                    });
                    $("#chatStowsTpl").tmpl(chats.reverse()).appendTo($('.pp-stows-content').children('.ui.list').empty());
                    $('.pp-stows-content .timeago').timeago();
                }
            });
        });
        $('.btn-get-chat-stows').hover(function() {

        }, function() {
            if (!$('.pp-stows-lock').hasClass('lock') && !$('.pp-translate:visible').size()) {
                $('.pp-stows').hide();
            }
        });

        $('.pp-stows-lock').click(function(event) {
            event.preventDefault();
            event.stopImmediatePropagation();
            $(this).toggleClass('lock unlock alternate');
        });
        // -------------------------------------------------------------------------------- chat stows end
        // -------------------------------------------------------------------------------- 快捷回复 start

        // 快速回复
        function quickReply(txt, id, username) {

            // [[回复#10](admin/dynamic?id=1){~xiweicheng}]
            var comment = '[[回复#{id}]({baseURL}admin/dynamic?id={id}){~{username}}]\n\n{text}';
            comment = comment.replace(/\{id\}/g, id)
                .replace(/\{baseURL\}/g, baseURL)
                .replace(/\{username\}/g, username)
                .replace(/\{text\}/g, txt);

            var content = comment;
            if (!$.trim(content)) {
                toastr.error('提交内容不能为空!');
                return;
            }

            if (isFetchNews) {
                toastr.warning('自动刷新沟通消息中,请稍后再尝试...');
                return;
            }

            var html = $('<div class="markdown-body"/>').html('<style>.markdown-body{font-size:14px;line-height:1.6}.markdown-body>:first-child{margin-top:0!important}.markdown-body>:last-child{margin-bottom:0!important}.markdown-body a.absent{color:#C00}.markdown-body a.anchor{bottom:0;cursor:pointer;display:block;left:0;margin-left:-30px;padding-left:30px;position:absolute;top:0}.markdown-body h1,.markdown-body h2,.markdown-body h3,.markdown-body h4,.markdown-body h5,.markdown-body h6{cursor:text;font-weight:700;margin:20px 0 10px;padding:0;position:relative}.markdown-body h1 .mini-icon-link,.markdown-body h2 .mini-icon-link,.markdown-body h3 .mini-icon-link,.markdown-body h4 .mini-icon-link,.markdown-body h5 .mini-icon-link,.markdown-body h6 .mini-icon-link{color:#000;display:none}.markdown-body h1:hover a.anchor,.markdown-body h2:hover a.anchor,.markdown-body h3:hover a.anchor,.markdown-body h4:hover a.anchor,.markdown-body h5:hover a.anchor,.markdown-body h6:hover a.anchor{line-height:1;margin-left:-22px;padding-left:0;text-decoration:none;top:15%}.markdown-body h1:hover a.anchor .mini-icon-link,.markdown-body h2:hover a.anchor .mini-icon-link,.markdown-body h3:hover a.anchor .mini-icon-link,.markdown-body h4:hover a.anchor .mini-icon-link,.markdown-body h5:hover a.anchor .mini-icon-link,.markdown-body h6:hover a.anchor .mini-icon-link{display:inline-block}.markdown-body hr:after,.markdown-body hr:before{display:table;content:""}.markdown-body h1 code,.markdown-body h1 tt,.markdown-body h2 code,.markdown-body h2 tt,.markdown-body h3 code,.markdown-body h3 tt,.markdown-body h4 code,.markdown-body h4 tt,.markdown-body h5 code,.markdown-body h5 tt,.markdown-body h6 code,.markdown-body h6 tt{font-size:inherit}.markdown-body h1{color:#000;font-size:28px}.markdown-body h2{border-bottom:1px solid #CCC;color:#000;font-size:24px}.markdown-body h3{font-size:18px}.markdown-body h4{font-size:16px}.markdown-body h5{font-size:14px}.markdown-body h6{color:#777;font-size:14px}.markdown-body blockquote,.markdown-body dl,.markdown-body ol,.markdown-body p,.markdown-body pre,.markdown-body table,.markdown-body ul{margin:15px 0}.markdown-body hr{overflow:hidden;background:#e7e7e7;height:4px;padding:0;margin:16px 0;border:0;-moz-box-sizing:content-box;box-sizing:content-box}.markdown-body h1+p,.markdown-body h2+p,.markdown-body h3+p,.markdown-body h4+p,.markdown-body h5+p,.markdown-body h6+p,.markdown-body ol li>:first-child,.markdown-body ul li>:first-child{margin-top:0}.markdown-body hr:after{clear:both}.markdown-body a:first-child h1,.markdown-body a:first-child h2,.markdown-body a:first-child h3,.markdown-body a:first-child h4,.markdown-body a:first-child h5,.markdown-body a:first-child h6,.markdown-body>h1:first-child,.markdown-body>h1:first-child+h2,.markdown-body>h2:first-child,.markdown-body>h3:first-child,.markdown-body>h4:first-child,.markdown-body>h5:first-child,.markdown-body>h6:first-child{margin-top:0;padding-top:0}.markdown-body li p.first{display:inline-block}.markdown-body ol,.markdown-body ul{padding-left:30px}.markdown-body ol.no-list,.markdown-body ul.no-list{list-style-type:none;padding:0}.markdown-body ol ol,.markdown-body ol ul,.markdown-body ul ol,.markdown-body ul ul{margin-bottom:0}.markdown-body dl{padding:0}.markdown-body dl dt{font-size:14px;font-style:italic;font-weight:700;margin:15px 0 5px;padding:0}.markdown-body dl dt:first-child{padding:0}.markdown-body dl dt>:first-child{margin-top:0}.markdown-body dl dt>:last-child{margin-bottom:0}.markdown-body dl dd{margin:0 0 15px;padding:0 15px}.markdown-body blockquote>:first-child,.markdown-body dl dd>:first-child{margin-top:0}.markdown-body blockquote>:last-child,.markdown-body dl dd>:last-child{margin-bottom:0}.markdown-body blockquote{border-left:4px solid #DDD;color:#777;padding:0 15px}.markdown-body table th{font-weight:700}.markdown-body table td,.markdown-body table th{border:1px solid #CCC;padding:6px 13px}.markdown-body table tr{background-color:#FFF;border-top:1px solid #CCC}.markdown-body table tr:nth-child(2n){background-color:#F8F8F8}.markdown-body img{max-width:100%}.markdown-body span.frame{display:block;overflow:hidden}.markdown-body span.frame>span{border:1px solid #DDD;display:block;float:left;margin:13px 0 0;overflow:hidden;padding:7px;width:auto}.markdown-body span.frame span img{display:block;float:left}.markdown-body span.frame span span{clear:both;color:#333;display:block;padding:5px 0 0}.markdown-body span.align-center{clear:both;display:block;overflow:hidden}.markdown-body span.align-center>span{display:block;margin:13px auto 0;overflow:hidden;text-align:center}.markdown-body span.align-center span img{margin:0 auto;text-align:center}.markdown-body span.align-right{clear:both;display:block;overflow:hidden}.markdown-body span.align-right>span{display:block;margin:13px 0 0;overflow:hidden;text-align:right}.markdown-body span.align-right span img{margin:0;text-align:right}.markdown-body span.float-left{display:block;float:left;margin-right:13px;overflow:hidden}.markdown-body span.float-left span{margin:13px 0 0}.markdown-body span.float-right{display:block;float:right;margin-left:13px;overflow:hidden}.markdown-body span.float-right>span{display:block;margin:13px auto 0;overflow:hidden;text-align:right}.markdown-body code,.markdown-body tt{background-color:#F8F8F8;border:1px solid #EAEAEA;border-radius:3px;margin:0 2px;padding:0 5px;white-space:nowrap}.markdown-body pre>code{background:none;border:none;margin:0;padding:0;white-space:pre}.markdown-body .highlight pre,.markdown-body pre{background-color:#F8F8F8;border:1px solid #CCC;border-radius:3px;font-size:13px;line-height:19px;overflow:auto;padding:6px 10px}.markdown-body pre code,.markdown-body pre tt{background-color:transparent;border:none}</style>' + simplemde.markdown(preParse(content))).wrap('<div/>').parent().html();

            var preMore = $('.btn-chat-pre-more').size() == 1;
            var $last = $('.chat .comments .comment').last();

            var $domBefore = preMore ? $('.btn-chat-pre-more') : $('.fm-reply');

            window.poll.pause(); // 因为提交消息,会顺便拉取新消息, 所以暂停轮询

            $.post('/admin/chat/create', {
                preMore: preMore,
                lastId: $last.size() == 0 ? -1 : $('.chat .comments .comment').last().attr('data-id'),
                baseURL: baseURL,
                usernames: parseUsernames(content).join(','),
                groups: parseGroupNames(content).join(','),
                content: content,
                contentHtml: html,
            }, function(data, textStatus, xhr) {
                if (data.success) {

                    toastr.success('提交成功!');

                    $('.btn-get-chat-news').hide(); // 已经顺便拉取了更新,所以隐藏获取更新按钮

                    if ($.isArray(data.data)) { // 不刷新追加
                        if (data.data.length == 0) {
                            return;
                        }

                        var $more = convertChat(data.data, null, null);
                        $more.insertBefore($domBefore);
                        jQuery(".timeago").timeago();
                    } else {
                        window.location.href = url('path') + '?scroll=1';
                    }

                } else {
                    toastr.error(data.data, '提交失败!');
                }
            }).always(function() {
                window.poll.reset(); // 重置轮询频率
            });

            // 标记对应消息@到自己的消息为已读
            $.post('/admin/chat/markAsReadedByChat/unmask', {
                chatId: id
            });
        }

        // 内置快速回复处理
        function quickReplyHandler(event) {

            event.preventDefault();
            var $btn = $(this);
            var txt = $btn.find('.text').text();

            var id = $btn.closest('.comment').attr('data-id');
            var username = $btn.closest('.comment').find('.content .author').attr('data-value');

            quickReply(txt, id, username);

        }

        $('body').on('click', '.chat .comments .comment .dd-quick-reply .menu > .item', quickReplyHandler);

        $('body').on('keyup', '.chat .comments .comment .dd-quick-reply input', function(e) {
            event.preventDefault();
            if (e.keyCode == 13) { // Enter
                var $input = $(this);
                var txt = $.trim($input.val());
                if (!txt) {
                    toastr.error('快速回复内容不能为空!')
                    return;
                }

                var id = $input.closest('.comment').attr('data-id');
                var username = $input.closest('.comment').find('.content .author').attr('data-value');

                quickReply(txt, id, username);
                $input.val('');
            }
        });

        $('body').on('click', '.chat .comments .comment .dd-quick-reply .ui.input .send.icon', function(e) {
            event.preventDefault();
            var $icon = $(this);
            var $input = $icon.next('input');
            var txt = $.trim($input.val());
            if (!txt) {
                toastr.error('快速回复内容不能为空!')
                return;
            }

            var id = $input.closest('.comment').attr('data-id');
            var username = $input.closest('.comment').find('.content .author').attr('data-value');

            quickReply(txt, id, username);
            $input.val('');
        });


        // -------------------------------------------------------------------------------- 快捷回复 end

    });

    // 热键处理
    jQuery(document).ready(function($) {

        var $currentComment = null;
        $(document).bind('keydown', 'alt+up', function() {
            event.preventDefault();
            if (!$currentComment || $currentComment.size() === 0) {
                $currentComment = $('.chat .comments .comment:first');
            } else {
                var $pr = $currentComment.prev('.comment');
                $currentComment = $pr.size() > 0 ? $pr : $currentComment;
            }

            if ($currentComment.size() === 1) {
                $('html, body, .ad-index-content').scrollTo($currentComment, {
                    offset: -50
                });
            }
        }).bind('keydown', 'alt+down', function() {
            event.preventDefault();
            if (!$currentComment || $currentComment.size() === 0) {
                $currentComment = $('.chat .comments .comment:last');
            } else {
                var $nx = $currentComment.next('.comment');
                $currentComment = $nx.size() > 0 ? $nx : $currentComment;
            }

            if ($currentComment.size() === 1) {
                $('html, body, .ad-index-content').scrollTo($currentComment, {
                    offset: -50
                });
            }
        }).bind('keydown', 'alt+ctrl+up', function() {
            event.preventDefault();
            $('.btn-scroll-up').click();
        }).bind('keydown', 'alt+ctrl+down', function() {
            event.preventDefault();
            $('.btn-scroll-down').click();
        });

        $('.chat .comments .comment').hover(function(event) {
            event.preventDefault();
            $currentComment = $(this);
        }, function(event) {
            event.preventDefault();
            $currentComment = null;
        });
    });

    // 收藏消息预览 & @消息预览预览
    jQuery(document).ready(function($) {

        $('.pp-stows-content, .pp-ats-content').on('mouseenter', 'i.preview.icon', function(event) {
            event.preventDefault();

            var $a = $(this);

            if ($a.closest('.pp-translate').size() != 0) {
                return;
            }

            $('.pp-translate').empty();

            $a.popup({
                popup: $('.pp-translate'),
                hoverable: true,
                inline: false,
                movePopup: false,
                position: 'right center',
                maxSearchDepth: 50,
                delay: {
                    show: 300,
                    hide: 300
                },
                onShow: function() {
                    var content = $a.closest('.item').attr('data-content');
                    $('<div class="markdown-body" />').html(parseMd(content)).css({
                        "width": "270px",
                        "height": "100px",
                        "overflow": "auto"
                    }).appendTo($(this).empty());
                }
            }).popup('show');
        });

    });
    </script>
</body>

</html>
